首页 > 解决方案 > 带外循环的内循环迭代

问题描述

我有一个简单的嵌套 while 循环情况,但我不确定如何在第二个循环内增加 numGuesses 以在第一个循环不再小于 5 时转义它。

while(numGuesses<5){
    while(!correct){
        cout << "\nGuess the number the computer randomply picked between 1 - 100: ";
        numGuesses++;
        cin >> guess;
        if(guess<number){
            cin.clear(); //clears input stream
            cin.ignore(256, '\n');
            cout << "\nSorry, your guess is too low";
        }
        else if (guess>number){
            cout << "\nSorry, your guess is too high";
        }
        else{
            cout << "\nYou guessed right, you win!";
            correct = !correct;
        }
    }
    
}
cout << "Sorry, you lost. The number is: " << number;

每次内部 while 循环迭代时,我都希望 numGuesses 增加,但我猜它不在其范围内?对不起菜鸟问题。完整代码:https ://ctxt.io/2/AAAgfdIGEg

标签: c++while-loop

解决方案


你应该只使用一个while循环!毕竟,您循环播放的内容是在提示您进行猜测。不需要在其中进行第二层循环。想一想您何时不想再要求猜测——当猜测达到 5 或当他们猜对时。那么你什么时候想继续要求猜测呢?当猜测数少于 5 且他们没有猜对时。另外,您想根据correct.

while(numGuesses<5 && !correct) {
    cout << "\nGuess the number the computer randomply picked between 1 - 100: ";
    numGuesses++;
    cin >> guess;
    if(guess<number){
        cin.clear(); //clears input stream
        cin.ignore(256, '\n');
        cout << "\nSorry, your guess is too low";
    }
    else if (guess>number){
        cout << "\nSorry, your guess is too high";
    }
    else{
        cout << "\nYou guessed right, you win!";
        correct = !correct;
    }
}
if (!correct) { // loop stopped before they got it correct
    cout << "Sorry, you lost. The number is: " << number;
}

您还需要"\n"s 或std::endls 在打印语句的末尾,否则您的代码将在一行上打印所有内容。


推荐阅读