While loop with multiple conditions in C++

馋奶兔 提交于 2021-02-05 05:31:08

问题


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.


回答1:


Use the || and/or the && operators to combine your conditions.

Examples:

1.

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

will loop while either a or b are true.

2.

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

will loop while both a and b are true.




回答2:


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 precedence will 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.




回答3:


do {

    srand (time(0));
    estrength = rand()%100);

    srand (time(0));
    strength = rand()%100);

} while(!estrength == 100 && !strength == 100 )



回答4:


do {
  // ...
} while (strength != 100 || estrength != 100)


来源:https://stackoverflow.com/questions/16568149/while-loop-with-multiple-conditions-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!