第四天第一个问题

发布时间 2023-04-16 20:58:18作者: 序章0

问题描述:编写一个程序,最多将10个值读到一个double数组中。程序遇到非数字输入时会结束输入,并输出这些数据的平均值及数组有多少个数据大于这个平均值。

解决思路:1.建立一个空间为11的double数组,建立一个循环体

2.输入值存储到double数组中

3.如果输入的值为非数字则跳出循环

4.建立另一个循环体计算数组中数据总值

5.计算出平均值

6.建立循环体比较数组中每一个数据和平均值的大小

7.输出平均值和大于平均值的数据个数

代码:

#include <iostream>
#include <cctype>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
double donation[10];
int len, i, j;
double sum, average, num;
string line;
cout << "Enter 10 donation!" << endl;
for (i = 0; i < 10; i++)
{
getline(cin, line, '\n');
len = line.size();
for (j = 0; j < len; j++)
{
if (isdigit(line[j]) == false && ispunct(line[j] == false))
{
cout << "not digit!" << endl;
}
}
donation[i] = atof(line.c_str());
sum += donation[i];
}
average = sum / i;
for (i = 0; i < 10; i++)
{
if (donation[i] > average)
{
num++;
}
}
cout << "The average = " << average << endl;
cout << "In this array has " << num << " large than avearge" << endl;
return 0;
}