![](/img/trans.png)
[英]c++ How do i end a while loop that add numbers without using a number as a trigger to end the loop
[英]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 > 0
和choice < 3
都是正确的,这就是我们想要的。 choice >= 3
(例如10),则循环将继续,因为choice > 0
为真 choice <= 0
(例如-1),则循环将继续,因为choice < 3
为真。 因此,对于任何choice
值(无论endgame
值如何),循环将始终继续。
此外,循环将继续 (而不是停止),而endgame
是true
,这是因为,一旦设置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.