代码:
/*
编写一个程序,最多将 10 个 donation 值读入到一个 double 数组中
(如果您愿意,也可以使用模板类 array)。
程序遇到非数字输入时结束输入,
并报告这些数字的平均值以及数组中有多少个数字大于平均值
*/
#include<iostream>
#include<cctype>
using namespace std;
const int Max = 10;
int main()
{
double donation[Max];
int i;
char ch;
int count = 0;
double sum = 0.0;
//将数据读入数组
for (i = 0; i < Max; i++)
{
cout << "Enter the num" << i + 1 << " : ";
cin >> ch;
if (!isdigit(ch))
break;
donation[i] = ch;
++count;
sum += donation[i];
}
if (count == 0) //数组中没有数据
cout << "No number.\a\n";
else
{
//输出均值
cout << sum / count << " = average of "
<< count << " numbers.\n";
//大于均值的数据的个数
int temp = 0;
for (i = 0; i < count; i++)
{
if (donation[i] > sum / count)
++temp;
}
cout << temp << " numbers > average.\n";
}
return 0;
}
结果:
Enter the num1 : 1
Enter the num2 : 2
Enter the num3 : 3
Enter the num4 : 4
Enter the num5 : e
50.5 = average of 4 numbers.
2 numbers > average.
想破脑袋没想明白,求解惑。