C++ primer plus
第六章 编程练习2
“编写一个程序,最多将10个donation值读入到一个double数组中。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值”
#include<iostream> #include<cctype> #include<string> int main() { const int SIZE = 10; bool flag; int count = 0,num = 0,len = 0; using namespace std; string donation; double group[SIZE] = {0}; double aver = 0,sum = 0; for(int i = 0;i < SIZE;i++) { cout << "Enter number :"; getline(cin,donation); len = donation.size(); for(int j = 0;j < len;j++) { if(!isdigit(donation[j]) && donation[j]!='.' ) { cout << "Input is not a number." << endl; i = SIZE; flag = 0; break; } else flag = 1; } if(flag) { group[i] = stod(donation,0); count = i+1; } } for(int k=0;k<=count;k++) { sum = sum + group[k]; } aver = sum/count; for (int k = 0; k < count; k++) { if(group[k] > aver) num++; } cout << "average: " << aver <<" There are " << num << " bigger than average." <<endl; return 0; }