-8 c++
我试图询问用户10岁学生的年龄,如果他们输入小于0或大于18的任何东西,我希望它将该值更改为0.
我做错了什么?
#include <iostream>
using namespace std;
int main()
int age [10];
int TotalAge, AverageAge;
for (int i = 0; i < 10; i++)
{
cout << "please enter the age of students:";
cin >> age[i];
if age[i] < 0 || age[i] >
cout << "An error was detected in your input, invalid age"; // print
age[i] = 0;
TotalAge += age[i]; // total age is the sum of age
AverageAge = TotalAge / 10;
cout << "Average age of class is: " << AverageAge << endl
}
Run Code Online (Sandbox Code Playgroud)
该
if ( age[i] < 0 || age[i] > 18 )
Run Code Online (Sandbox Code Playgroud)
你应该把平均值放在循环之外.
//Initialize variables
int TotalAge = 0, AverageAge = 0;
for (int i = 0; i < 10; i++)
{
cout << "please enter the age of students:";
cin >> age[i];
if ( age[i] < 0 || age[i] > 18 )
{
cout << "An error was detected in your input, invalid age"; // print
age[i] = 0;
}
TotalAge += age[i]; // total age is the sum of age
}
//Calculate average outside
AverageAge = TotalAge / 10;
cout << "Average age of class is: " << AverageAge << endl;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |