编写一个程序,最多将10 个donation值读入到一个double数组中。如果程序遇到非数字输入时将结束输入,并报告这些数的平均值以及数组中有多少个数字大于平
编写一个程序,最多将10 个donation值读入到一个double数组中。如果程序遇到非数字输入时将结束输入,并报告这些数的平均值以及数组中有多少个数字大于平均值代码1:#include<iostream>
#include<cctype>
const int SIZE = 10;
int main()
{
using namespace std;
double* pd = new double[SIZE];
int i = 0;
while (i < SIZE)
{
cin >> pd[i];
if (!isdigit(pd[i]))
break;
i++;
}
if (i == 0)
cout << "There is no data." << endl;
else
{
double average, sum;
int count = 0;
sum = 0;
for (int i = 0; i < SIZE; i++)
sum += pd[i];
average = sum / SIZE;
cout << "Average: " << float(average) << endl;
for (int i = 0; i < SIZE; i++)
{
if (average < pd[i])
count++;
}
cout << "Number(beyond average): " << count << endl;
}
delete[] pd;
return 0;
}
代码2:
#include<iostream>
#include<cctype>
const int SIZE = 10;
int main()
{
using namespace std;
double* pd = new double[SIZE];
int i = 0;
while (i < SIZE)
{
cin >> pd[i];
i++;
}
if (i == 0)
cout << "There is no data." << endl;
else
{
double average, sum;
int count = 0;
sum = 0;
for (int i = 0; i < SIZE; i++)
sum += pd[i];
average = sum / SIZE;
cout << "Average: " << float(average) << endl;
for (int i = 0; i < SIZE; i++)
{
if (average < pd[i])
count++;
}
cout << "Number(beyond average): " << count << endl;
}
delete[] pd;
return 0;
}
若删除代码1中
if (!isdigit(pd[i]))
break;
这个程序就可以正确运行;
但是我想通过
if (!isdigit(pd[i]))
break;
来判断输入的是否为数字。
我代码1 错在哪了?
[此贴子已经被作者于2021-5-15 20:10编辑过]