繁体   English   中英

我该如何结束while循环?

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

这可能是一个非常新手的问题,但是我只是在为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;
}

由于您使用的是OR|| ):

  • 如果0 < choice < 3 ,则循环显然会继续,因为choice > 0choice < 3都是正确的,这就是我们想要的。
  • 但是,如果choice >= 3 (例如10),则循环将继续,因为choice > 0为真
  • 如果choice <= 0 (例如-1),则循环将继续,因为choice < 3为真。

因此,对于任何choice值(无论endgame值如何),循环将始终继续。

此外,循环将继续 (而不是停止),而endgametrue ,这是因为,一旦设置choice给出的不是1或2的值。

如果将其&& AND&& )并反转endgame检查,则该检查应起作用:

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

但是实际上, choice > 0 && choice < 3 &&是不必要的,因为一旦这些条件之一成立,您就设置了endgame

while (endgame == false);

可以简化为:

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

当满足退出条件时,这会将endgame设置为true,然后循环返回,因为您检查endgame是否为而非假。 你要

} while (!endgame);

代替。

这里:

if(endgame) break;

尝试将其放在循环的末尾。

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

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

暂无
暂无

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

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