c++ 使用外部循环的内部while循环迭代

9ceoxa92  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(157)

我有一个简单的嵌套while循环,但我不确定如何在第二个循环中递增numGuesses,以便在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增加,但我猜它不在它的范围内?

06odsfpq

06odsfpq1#

你应该只用一个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;
}

您还希望在print语句的末尾使用"\n" s或std::endl s,否则代码将在一行中打印所有内容。

bqucvtff

bqucvtff2#

你不需要两次...

while(numGuesses < 5 && !correct)
{
       // your logic here
}

之后,您可以检查变量correctnumGuesses。例如:

if(!correct)
    // your code

相关问题