简体   繁体   English

我该如何结束while循环?

[英]How do I end this do while loop?

This is probably a very newbie question but I am just practising classes for C++ and cannot seem to get this do while loop to end under a boolean condition. 这可能是一个非常新手的问题,但是我只是在为C ++练习类,似乎无法在布尔条件下使while循环结束。

int main()
{
    bool endgame = false;
    string x;
    int choice;
    cout << "please choose the colour you want your bow to be:\n";
    cin >> x;
    Bow bow1(x);
    do
    {
        cout << "please choose what you would like to do\n";
        cout << "(1 draw bow\n(2 fire bow\n(3 end game";
        cin >> choice;

        if (choice == 1)
        {
            bow1.Draw();
        }
        else if (choice == 2)
        {
            bow1.Fire();
        }
        else
        {
            endgame = true;
        }
    }
    while (choice > 0 || choice < 3 || endgame == true);
    return 0;
}

Since you're using OR ( || ): 由于您使用的是OR|| ):

  • If 0 < choice < 3 , the loop will obviously continue since both choice > 0 and choice < 3 are true, this is what we want. 如果0 < choice < 3 ,则循环显然会继续,因为choice > 0choice < 3都是正确的,这就是我们想要的。
  • However, if choice >= 3 (say 10), the loop will continue since choice > 0 is true 但是,如果choice >= 3 (例如10),则循环将继续,因为choice > 0为真
  • and if choice <= 0 (say -1), the loop will continue since choice < 3 is true. 如果choice <= 0 (例如-1),则循环将继续,因为choice < 3为真。

Thus the loop will always continue for any value of choice (regardless of endgame 's value). 因此,对于任何choice值(无论endgame值如何),循环将始终继续。

Also, the loop will continue (instead of stopping) while endgame is true , which is set as soon as choice is given a value of not 1 or 2. 此外,循环将继续 (而不是停止),而endgametrue ,这是因为,一旦设置choice给出的不是1或2的值。

If you make it AND ( && ) and reverse the endgame check, it should work: 如果将其&& AND&& )并反转endgame检查,则该检查应起作用:

while (choice > 0 && choice < 3 && endgame == false);

But really the choice > 0 && choice < 3 && is unnecessary since you're setting endgame once either of those conditions hold. 但是实际上, choice > 0 && choice < 3 &&是不必要的,因为一旦这些条件之一成立,您就设置了endgame

while (endgame == false);

This can be simplified to: 可以简化为:

while (!endgame);
do {
    if (exit_condition)
        endgame = true;
} while (endgame == true);

This will set endgame to true when the exit condition is met, then loop back, because you check for endgame being true and not false. 当满足退出条件时,这会将endgame设置为true,然后循环返回,因为您检查endgame是否为而非假。 You want 你要

} while (!endgame);

instead. 代替。

Here: 这里:

if(endgame) break;

Try putting that at the end of your loop. 尝试将其放在循环的末尾。

只要您的endgame是假的,您想要的就是保持循环,因此您只需要在while语句中更改测试,如下所示:

while (choice > 0 || choice < 3 || endgame == false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM