C++中具有多个条件的while循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16568149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
While loop with multiple conditions in C++
提问by ConMaki
How would I make a loop that does the loop until one of multiple conditions is met. For example:
我将如何制作一个循环,直到满足多个条件之一为止。例如:
do
{
srand (time(0));
estrength = rand()%100);
srand (time(0));
strength = rand()%100);
} while( ) //either strength or estrength is not equal to 100
Kind of a lame example, but I think you all will understand.
有点蹩脚的例子,但我想你们都会明白的。
I know of &&, but I want it to only meet one of the conditions and move on, not both.
我知道&&,但我希望它只满足其中一个条件并继续前进,而不是同时满足这两个条件。
回答by Daniel Daranas
Use the ||
and/or the &&
operators to combine your conditions.
使用||
和/或&&
运算符组合您的条件。
Examples:
例子:
1.
1.
do
{
...
} while (a || b);
will loop while either a
or b
are true.
将循环而无论a
或者b
是真实的。
2.
2.
do
{
...
} while (a && b);
will loop while both a
and b
are true.
将循环而这两个a
和b
是真实的。
回答by BoBTFish
while ( !a && !b ) // while a is false and b is false
{
// Do something that will eventually make a or b true.
}
Or equivalently
或等效地
while ( !( a || b ) ) // while at least one of them is false
This table of operator precedencewill be useful when creating more complicated logical statements, but I generally recommend bracketing the hell out of it to make your intentions clear.
在创建更复杂的逻辑语句时,此运算符优先级表将很有用,但我通常建议将其括起来以明确您的意图。
If you're feeling theoretical, you might enjoy De Morgan's Laws.
如果您感觉理论化,您可能会喜欢德摩根定律。
回答by flavian
do {
srand (time(0));
estrength = rand()%100);
srand (time(0));
strength = rand()%100);
} while(!estrength == 100 && !strength == 100 )
回答by broetchen
do {
// ...
} while (strength != 100 || estrength != 100)