题解 | #记负均正#
记负均正
http://www.nowcoder.com/practice/6abde6ffcc354ea1a8333836bd6876b8
题意:
输入n个整数。输出为n个整数中负数的个数,和所有正整数的平均值,结果保留一位小数。
解法(循环,判断)
记变量
表示负数的数量,
变量
表示正数之和,
变量
表示正数的数量。
显然上述三个变量只需要扫描一遍整个数组即可求出来,最后按照题意计算输出即可。
代码:
#include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); int n; while(cin>>n){ int ans1=0; int ans2=0,cnt2=0; for(int i=1;i<=n;i++){ int x; cin>>x; if(x<0){ ans1++;//负数 }else if(x>0){ ans2+=x;//正数 cnt2++; } } cout<<ans1<<" "<<fixed<<setprecision(1)<<(double)ans2/cnt2<<endl;//输出答案 } return 0; }时间复杂度:
空间复杂度:
,程序中没有开额外数组,也没有递归调用,故空间复杂度为