2012-07-03 41 views
-4

只是做一個小程序開始C++和編譯器說,有一個沒有如果引用while循環在main中,但顯然不是這樣,我不能明白爲什麼。它工作正常,如果我刪除while循環。C++錯誤:其他沒有以前如果

#include <iostream> 
using namespace std; 

int number; 

int arithmetic(int num) 
{ 
if(num > 20) 
    num = num * 5; 
else 
    num = 0; 
return (num); 
} 

int main() 
{ 
int wait; 
cout << "I will take any number providing it is higher than twenty" << endl; 
cout << "and I will multiply it by 5. I shall then print every number" << endl; 
cout << "from that number backwards and say goodbye." << endl; 
cout << "Now please give me your number: " << endl; 
cin >> number; 
int newnum = arithmetic(number); 
if (newnum != 0) 
    cout << "Thank you for the number, your new number is" << newnum << endl; 
    while(newnum > 0){ 
    cout << newnum; 
    --newnum; 
    } 
    cout << "bye"; 
else 
    cout << "The number you entered is not greater than twenty"; 
cin >> wait; 
return 0; 
} 
+0

只有當你仔細閱讀了該教程... – 2012-07-03 05:58:05

+0

我幾次讀完。去http://www.cplusplus.com/doc/tutorial/control/他們沒有括號寫在那裏。 –

+1

@DamianStelucir如果你沒有注意到,你引用的頁面說:「如果我們希望在條件爲真的情況下執行一個以上的語句,我們可以使用大括號{}指定一個塊:」 – WiSaGaN

回答

2

你需要if (newnum != 0){else}

2

這種類型的結構是錯誤的:

if(something) 
    line1; 
    line2; // this ; disconnects the if from the else 
else 
    // code 

你需要像

if (something) { 
    // more than one line of code 
} else { 
    // more than one line of code 
} 
3

你缺少括號。你有

if (newnum != 0) 
cout << "Thank you for the number, your new number is" << newnum << endl; 
while(newnum > 0){ 
cout << newnum; 
--newnum; 
} 
cout << "bye"; 
else 
cout << "The number you entered is not greater than twenty"; 

,而你應該有:

if (newnum != 0) 
{ 
    cout << "Thank you for the number, your new number is" << newnum << endl; 
    while(newnum > 0){ 
    cout << newnum; 
    --newnum; 
    cout << "bye"; 
} 
else 
    cout << "The number you entered is not greater than twenty"; 

如果你在if語句有一個以上的操作,你應該總是用括號。如果你只有一個,你可以省略它們(就像在這個「else」語句中)。