我有几个问题需要修复。该程序找到用户所需数字的平均值。例如,如果他们输入3然后1,2,3则平均值为2。 首先,如果输入零,我的程序应该停止。因此,如果我将3作为将被平均的整数的数量,然后我输入1,2,0它应该停止并且不计算平均值。 另外,我需要考虑负数。
#include <iostream>
using namespace std;
double avgVal(int, int);
int main()
{
int amountOfCases;
cin >> amountOfCases;
int * numbers = new int[amountOfCases];
int sum = 0;
while(numbers !=0)
{
for (int i = 0; i<amountOfCases; i++)
{
cin >> numbers[i];
sum = sum + numbers[i];
}
cout<<avgVal(sum, amountOfCases)<<endl;
delete[] numbers;
}
system("pause");
return 0;
}
double avgVal(int sum, int amountOfCases)
{
return sum / (double)amountOfCases;
}
答案 0 :(得分:0)
在添加while
循环时,不确定您的想法。考虑到你试图解决的问题,没有必要。
更改行:
while(numbers !=0)
{
for (int i = 0; i<amountOfCases; i++)
{
cin >> numbers[i];
sum = sum + numbers[i];
}
cout<<avgVal(sum, amountOfCases)<<endl;
delete[] numbers;
}
到
for (int i = 0; i<amountOfCases; i++)
{
cin >> numbers[i];
if ( numbers[i] == 0 )
{
exit(1); // Exit with a non-zero status, indicating failure.
}
sum = sum + numbers[i];
}
cout<<avgVal(sum, amountOfCases)<<endl;
delete[] numbers;