-9

我试图询问 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
   }
4

2 回答 2

5

if ( age[i] < 0 || age[i] > 18 )

你应该把平均值放在循环之外。

//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;
于 2012-06-02T09:17:59.517 回答
3

并且 main 函数中的所有内容都必须在 { } 之间

于 2012-06-02T09:20:04.193 回答