首页 > 试题广场 >

编写一个程序,最多将10个donation值读入到一个dou

[问答题]
编写一个程序,最多将10个donation值读入到一个double数组中(如果您愿意,也可使用模板类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
#include<iostream>
#include<cctype>
#include<string>
int main()
{
    using namespace std;
    double donation[10];
    int len, k;
    double sum = 0, average = 0, num = 0;
    string line;
    cout << "Please Enter double donation : " << endl;
    for (k = 0; k < 10; k++)
    {
        getline(cin, line, '\n');
        len = line.size(); 
        for (int i = 0; i < len; i++)
            {
            if (!isdigit(line[i]))
                cout << "This is not a digit." << endl;
            }
        donation[k] = stod(line);
        sum += donation[k];
    }
    average = sum / k;
    for (int j = 0; j < 10; j++)
    {
        if (donation[j] > average)
            num++;
    }
    cout.precision(2);
    cout.setf(ios::showpoint);
    cout << "The average of these number is " << average << endl;
    cout << "The sum of these number is " << sum << endl;
    cout << "In this array has " << num << " number large than average." << endl;
    return 0;
}
编辑于 2022-03-06 10:32:51 回复(0)