C++ If语句错误:expected';' 在'{'之前

gr3*_*bo1 1 c++ if-statement

我写这篇文章是为了好玩:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试用g ++编译它,但我得到这个错误:

arsenalNorwich.cpp: In function, 'int main'
arsenalNorwich.cpp:15:30: error: expected ';' before '{' token
Run Code Online (Sandbox Code Playgroud)

我不知道我做错了什么,我学校的CS导师也没有.虽然它只是为了好玩,但它让我发疯.

tao*_*ocp 8

你错过了一个if:

  else if (Norwich > Arsenal)
  ///^^^if missing
Run Code Online (Sandbox Code Playgroud)

同时,放不好

 int Arsenal = rand()%3;
 int Norwich = rand()%3;
Run Code Online (Sandbox Code Playgroud)

之前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;
Run Code Online (Sandbox Code Playgroud)

  • +1正确,但如果它不是<并且不是==,可以说缺少`if`或*extra*表达式;) (2认同)