2013-04-13 56 views
1

我在寫這一點的樂趣:C++如果語句錯誤:預期';'之前,「{」令牌

#include <iostream> 
#include <cstdlib> 
using namespace std; 

int Arsenal = rand()%3; 
int Norwich = rand()%3; 

int main() { 
    if (Arsenal > Norwich) { 
    cout << "Arsenal win the three points, they are in the Top Four"; 
    return 0; 
    } else if (Arsenal == Norwich) { 
    cout << "The game was a draw, both teams gained a point"; 
    return 0; 
    } else (Norwich > Arsenal) { 
     cout << "Norwich won, Arsenal lost"; 
     return 0; 
    } 
} 

,我試圖編譯它在G ++,但我得到這個錯誤:

arsenalNorwich.cpp: In function, 'int main' 
arsenalNorwich.cpp:15:30: error: expected ';' before '{' token 

我不知道我做錯了,我的學校的CS導師也沒有。儘管這只是爲了好玩,但卻讓我發瘋。

+2

導師不? ............ – chris

+0

*「我不知道我做錯了什麼」 * - 你選擇了一所學校與誰不知道C++導師,通過它的聲音! +1發佈一個格式良好的問題,儘管是全新的stackoverflow。 – JBentley

+1

未來,告訴我們哪一行是第15行。保存每個人不必計算行數。 –

回答

8

你錯過了一個if這裏:

else if (Norwich > Arsenal) 
    ///^^^if missing 

同時,也不好把

int Arsenal = rand()%3; 
int Norwich = rand()%3; 

main之前。另一點是你應該在撥打rand()之前先設置隨機種子。

if-else可以如下簡化:

if (Arsenal > Norwich) { 
    cout << "Arsenal win the three points, they are in the Top Four"; 
} else if (Arsenal == Norwich) { 
    cout << "The game was a draw, both teams gained a point"; 
} else { //^^^no need to compare values again since it must be Norwich > Arsenal 
     //when execution reaches this point 
    cout << "Norwich won, Arsenal lost"; 
} 
return 0; 
+2

+1正確,但如果不是<且不是==,則可以說缺少了'if'或* extra *表達式;} – msw

+1

@msw同意了,更新了該帖子。 – taocp

+1

@msw我會更進一步,並且說'else'應該是*首選的* over else else(expression)' - 它的可讀性更強,因爲讀者可以很容易地找出在每個可能的情況下會發生什麼*,因爲你提供了一個最終的全部。 – JBentley

相關問題