记负均正
描述
首先输入要输入的整数个数n,然后输入n个整数。输出为n个整数中负数的个数,和所有正整数的平均值,结果保留一位小数。0既不是正整数,也不是负数,不计入计算
输入描述:
本题有多组输入用例。
首先输入一个正整数n,
然后输入n个整数。
输出描述:
输出负数的个数,和所有正整数的平均值。
首先输入要输入的整数个数n,然后输入n个整数。输出为n个整数中负数的个数,和所有正整数的平均值,结果保留一位小数。0既不是正整数,也不是负数,不计入计算
输入描述:
本题有多组输入用例。
首先输入一个正整数n,
然后输入n个整数。
输出描述:
输出负数的个数,和所有正整数的平均值。
方法一
思路分析
根据输入的整数个数,定义数组存储,之后遍历数组,遇到数组元素小于0的进行计数,遇到大于0的进行累加并计数,最后输出负数的个数,求出正整数的平均值
图解
| $x_i$ | $1$ | $3$ | $5$ | $0$ | $4$ | $-1$ | $output$ |
| $count_id$ |
|
$1$ |
$负数个数:1$ |
||||
| $sum$ | $1$ | $4$ | $9$ |
|
$13$ |
|
$平均值:3.25$ |
| $cout_pos$ | $1$ | $2$ | $3$ |
|
$4$ |
|
|
核心代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n=0;
while(cin>>n)
{
vector<int>temp(n,0);
int m=0;
int count_id=0;
int count_pos=0;
double sum=0;
for(int i=0;i<n;i++)
{
cin>>temp[i];
}
for(int i=0;i<n;i++)
{
if(temp[i]<0) count_id++;
if(temp[i]>0)
{
count_pos++;
sum+=temp[i];
}
}
cout<<count_id<<" "<<setiosflags(ios::fixed)<<setprecision(1)<<sum/count_pos<<endl;
}
return 0;
}
复杂度分析
- 时间复杂度:时间复杂度为$O(n)$
- 空间复杂度:空间复杂度为$O(n)$
方法二
思路分析
方法一中其实并不需要记录元素到数组中,因此直接对输入元素小于0的进行计数,遇到大于0的进行累加并计数,最后输出负数的个数,求出正整数的平均值
核心代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n=0;
while(cin>>n)
{
int m=0;
int count_id=0;//记录负数的个数
int count_pos=0;//记录正数的个数
double sum=0;//正整数的和
for(int i=0;i<n;i++)
{
cin>>m;
if(m<0) count_id++;
else if(m>0)
{
count_pos++;
sum+=m;
}
}
cout<<count_id<<" "<<setiosflags(ios::fixed)<<setprecision(1)<<sum/count_pos<<endl;
}
return 0;
}
复杂度分析
- 时间复杂度:时间复杂度为$O(n)$
- 空间复杂度:空间复杂度为$O(1)$

京公网安备 11010502036488号