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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:28:17  来源:igfitidea点击:

While loop with multiple conditions in C++

c++do-while

提问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 aor bare true.

将循环而无论a或者b是真实的。

2.

2.

do
{
...
} while (a && b);

will loop while both aand bare true.

将循环而这两个ab是真实的。

回答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)