📅  最后修改于: 2020-09-25 06:00:16             🧑  作者: Mango
#include
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
输出
Enter the numbers of data: 6
1. Enter number: 45.3
2. Enter number: 67.5
3. Enter number: -45.6
4. Enter number: 20.34
5. Enter number: 33
6. Enter number: 45.6
Average = 27.69
如果数据数为1到100,则此程序将计算平均值。
如果用户输入的n
值大于100或小于100,则执行while循环,要求用户输入n
值直到1到100之间。
当用户输入数字时,随后计算总和并将其存储在变量sum
。
存储所有数字后,将计算并显示average
。