题意:
输入 n 个整型数,统计其中的负数个数并求所有非负数的平均值,结果保留一位小数。
如果没有非负数,则平均值为0。
方法一:
直接模拟
思路:遍历每个数。
分别对负数和非负数计数,并对非负数求和。
#include <bits/stdc++.h>
using namespace std;
int main(){
int cnt1=0,cnt2=0;//计数
double s=0;//非负数的和
int x;
while(cin >> x){
if(x<0){//负数计数
cnt1++;
}else{//非负数计数并且非负数累加
cnt2++;
s+=x;
}
}
printf("%d\n%.1f\n",cnt1,cnt2==0?0:s/cnt2);
return 0;
}
时间复杂度:
空间复杂度:![]()
方法二:
存储模拟
思路:先将输入的数用数组存储,
再枚举每个数,对负数计数和非负数求和。
#include <bits/stdc++.h>
using namespace std;
int n,a[50005];
int cnt;//对负数计数
double s=0;//非负数的和
int main(){
while(cin >> a[n++]);//输入
n--;
for(int i=0;i<n;i++){//遍历每个数
if(a[i]<0){//负数计数
cnt++;
}else{//非负数累加
s+=a[i];
}
}
printf("%d\n%.1f\n",cnt,(n-cnt)==0?0:s/(n-cnt));
return 0;
}
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号