如何在每次运行“ return main();”时使变量增加

0 c++ variables

Level每次使用时我需要增加1return main();

我需要一些我没有在中设置变量的地方int main(),或者level = 0;每次都绕过但第一次绕过的地方,但是我不知道该怎么做。

如果有一些编码向导,如果您能帮助我,我将不胜感激(哦,是的,我Level在欢迎信息中用代替了"placeholder")。

我尝试制作一个新文件,将其放置在上方int main() {},使用变量在结束代码之前使用它使其在开始之前将其设置为1,以便仅level在其他变量(称为reset)为0时将其设置为0。1,但这没有用,因为reset每次将0都重新开始。那没有用,所以我摆脱了它。

int main()
{
    int level;
    level = 0;

    system("cls");
    //varibles

    int secret, guess;
    // color
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 4);

    //the number that you guess!
    srand(time(NULL));
    secret = rand() % 100 - 0;

    cout << "   Number Guessing Game!" << endl;
    cout << "----------------------------------" << endl;
    cout << endl;
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 6);
    cout << "Welcome my name is Luffy Computron. your currant level is " << "placeholder" << endl;
    cout << " I will randomly pick a number between 0 and 100" << endl;
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 22);
    cout << "Take a guess" << endl;
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
    cout << "Guess:";
    cin >> guess;
    while (guess != secret) {
        if (guess > secret) {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 6);
            cout << "Too large. Try again." << endl;
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
        }
        if (guess < secret) {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 6);
            cout << "Too small. Try again." << endl;    
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
        }
        cout << "Guess:";
        cin >> guess;
    }

    if (guess == secret) {
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 6);
        cout << "Congradulations!" << endl;
        if (level == 1) {
            cout << "you are now an untrained aprentice of the computron team";
            cout << "to become an aprentice play 4 more times!";
        }
    }
    Sleep(2000);
    return main();
}
Run Code Online (Sandbox Code Playgroud)

它应该level每次运行都会改变一个,return main(); 但始终保持在1。

Ted*_*gmo 5

不要打电话main()。在要重复的内容周围使用循环:

int main() {
    bool running = true;
    int level = 0;

    while(running) {

        //...

        ++level;
    } // <- your old return main(); replaced with }
}
Run Code Online (Sandbox Code Playgroud)

这将在while(running) {和中的}标记之间循环,直到您更改runningfalse。您还可以使用break;退出最近的环绕循环,如下所示:

    while(true) {
        if(some_condition) break;
    }
Run Code Online (Sandbox Code Playgroud)

它应该在每次运行return main()时将级别更改一次。但它保持在1。

在您当前的代码中,您level = 0;在的开头进行分配main()。通过使用上述循环,该分配将仅发生一次。