2012-06-02 281 views
-9

我想要問10歲的學生的用戶,如果他們輸入小於0或超過18的任何東西,我希望它將該值更改爲0.C++,我做錯了什麼?

我做錯了什麼?

#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 
    } 
+0

我錯過了18 - 如果年齡[I] <0 ||年齡[i]> 18 –

+0

在尋求幫助時,除了想要發生的事情外,還要描述實際發生的事情(包括任何錯誤消息)。 – outis

回答

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; 
+1

當你在它的時候,不妨更正主體缺失的{}。 – Mat

+0

@索被Sorin覆蓋。 –

3

,一切都在主函數必須在{}

+0

爲什麼他給int TotalAge和AverageAge加0? –

+0

,因爲當你在main中聲明一個變量時,它會自動初始化一個值...假設它是-12 ...當你在你的總年齡中加2時,你會得到--10,這是不好的...所以你必須確保你從0開始......所以,當你添加2時,結果將是2 ... –

+0

並嘗試寫入縮進,就像Luchian ...這意味着當你在大括號 - {} - 你必須向右寫一點......實際上,右邊一個「選項卡」...將你的代碼與Luchian的代碼進行比較,你會看到不同之處......閱讀代碼,尤其是當你有很多代碼行... –