你将如何在 C++ 中将计数器控制循环与标志控制循环结合起来?

How would you combine a counter controlled loop with a flag controlled loop in c++?

我正在用 C++ 进行猜数游戏,我被要求将计数器循环与标志控制循环结合起来。我正在使用随机数生成器,用户可以猜到的最少次数是 5 次,在用户猜到 5 次之后,程序应该以计算机生成的数字作为响应。唯一的问题是我无法成功地将计数器与标志循环结合起来,并且在编译时,我的程序只要求使用猜测,并且在迭代 5 次后结束循环并且不响应计算机生成的编号。我很确定这与我如何安排计数器控制循环有关,但我在设置它时遇到了麻烦,以便计数器在标志控制循环内递增并为标志控制循环提供有效语句。我尝试搜索更多标志控制循环和计数器控制循环的示例,因为我对这些概念还很陌生,但无法修复我的程序。 这是我的代码的一部分:

while (!correct == (numGuesses < 5))
    {
        cout << "Guess the number the computer randomly picked between 1 - 100: ";
        cin >> guess;

        if (guess == number)
        {
            cout << "You guessed right, you win!" << endl << endl;
            correct = true;
        }
        else if (guess > number)
        {
        cout << "Sorry, your guess is too high" << endl;
        numGuesses += 1;
        }
        else if (guess < number)
        {
        cout << "Sorry, your guess is too low" << endl;
        numGuesses += 1;
        }
        else if (numGuesses == 5)
        {
            cout << "Sorry, you lost. The number is: " << number << endl << endl;
        }

    }

首先,我相信你在 while 循环中的条件应该是 !correct && (numGuesses < 5),因为这两种情况都意味着你不应该继续。

在 5 次错误猜测后没有打印出随机生成的数字的原因是您使用的是 else if。由于 guess == numberguess > numberguess < number 总是这样,因此您永远不会输入最后一个 else if。因此,将检查 if numGuesses == 5 的最后一个 else if 更改为简单的 if 语句,一切都应该有效。

The only problem is that I haven't been able to successfully combined the counter with the flag loop

您有两个条件:counter < limitcorrect == false

只要两个条件都为真,您想继续循环。

我们有 logical operators 用于组合布尔 (true/false) 表达式。

在这种情况下你想说X(是真的)Y(是真的)("is true"部分隐含在布尔表达式中),拼写为

X && Y

或者在这种情况下

(numGuesses < 5) && (!correct)