計負均正
題目描述
從鍵盤輸入任意20個整型數,統計其中的負數個數並求所有正數的平均值。
保留兩位小數
輸入
輸出
樣例輸入
1 2 3 4 5 6 7 8 9 10
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10
樣例輸出
10
5.50
代碼
#include<iostream>
#include<iomanip> using namespace std; int main() { int n=20; int num=0; int i=0; double average=0; int x; int sum=0; cout<<"請輸入20個整型數"<<endl; while(n--) { cin>>x; if(x<0) { num++; } else { i++; sum+=x; average=(double)sum/i; } } cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout<<"負數的個數爲"<<num<<endl; cout<<"所有正數的平均值爲"<<average<<endl; return 0;
}
體會:
cout方法: