第一个c ++可能出现语法错误

时间:2015-01-31 00:50:04

标签: c++

嘿大家我正在为一所学校的项目工作,我很确定代码本身是正确的,但我不知道为什么我的IDE会出现错误。

该项目是一个简单的猜数游戏。

表示:

In function 'int main()':|
35|error: 'elif' was not declared in this scope|
35|error: expected ';' before '{' token|
37|error: expected ';' before '{' token|
40|error: 'else' without a previous 'if'|

这是我的代码:

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

main(){
    int upper = 100;
    int lower = 1;
    int guess;
    int answer;
    int turnCounter = 0;


    string name;

    cout << "Hello, welcome to the number game!" << endl;
    cout << "What's your name? " << endl;
    cin >> name;
    cout << "Nice to meet you " << name << "!" << endl;
    cout << "Ok let's get started, think of a number between 1 and 100, and I'll try to guess it!"
         << "If my guess is too high type a 1, if it is too low type a 0 or 10 if I get it right!" << endl;

    bool keepgoing = true;
    while (keepgoing){
            turnCounter ++;
            guess = (upper + lower)/ 2;
            cout << "Is the answer " << guess << "?" << endl;
            cin >> answer;
            if (answer == 1){
                upper = guess;
            } elif (answer == 0){
                lower = guess;
            } elif (answer == 10){
                cout << "Great! I'm so Awesome!" << endl;
                keepgoing = False;
            } else {
                cout << "Something went wrong, answer again: ";
                cin >> answer;
            }//end if loop
    } //end of while loop
}//end main

3 个答案:

答案 0 :(得分:8)

  1. main ()应为int main ()
  2. False应为false
  3. elif应为else if
  4. 这使得代码至少可以编译。

    在您的C ++知识水平上,您几乎可以相信编译器是正确的。如果它说你的代码坏了,那就是。

答案 1 :(得分:1)

你来自Python背景吗?

首先,没有elif这样的关键字。

您应该使用else if之类的

if (answer == 1){
    upper = guess;
} else if (answer == 0){
    lower = guess;
}

此外,您应将False声明为false

最后,您尚未为main声明int返回类型。它应该被声明为。

int main()
{
    // your code here
}

答案 2 :(得分:0)

如果不是elif,请尝试其他

 if (answer == 1){
        upper = guess;
    } else if (answer == 0){
        lower = guess;