你如何在 C++ 中创建一个重复直到循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1077216/
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
How do you Make A Repeat-Until Loop in C++?
提问by Adrien
How do you Make A Repeat-Until Loop in C++? As opposed to a standard While or For loop. I need to check the condition at the end of each iteration, rather than at the beginning.
你如何在 C++ 中创建一个重复直到循环?与标准的 While 或 For 循环相反。我需要在每次迭代结束时检查条件,而不是在开始时。
回答by Adrien
do
{
// whatever
} while ( !condition );
回答by Zifre
When you want to check the condition at the beginning of the loop, simply negate the condition on a standard while
loop:
当您想在循环开始时检查条件时,只需在标准while
循环中否定条件:
while(!cond) { ... }
If you need it at the end, use a do
... while
loop and negate the condition:
如果最后需要它,请使用do
...while
循环并否定条件:
do { ... } while(!cond);
回答by weiwangchao
You could use macros to simulate the repeat-until syntax.
您可以使用宏来模拟重复直到语法。
#define repeat do
#define until(exp) while(!(exp))
回答by Kehlin Swain
For an example if you want to have a loop that stopped when it has counted all of the people in a group. We will consider the value X to be equal to the number of the people in the group, and the counter will be used to count all of the people in the group. To write the
例如,如果您希望循环在对组中的所有人员进行计数时停止。我们将值 X 视为等于组中的人数,并且计数器将用于计算组中的所有人数。写
while(!condition)
而(!条件)
the code will be:
代码将是:
int x = people;
int counter = 0;
while(x != counter)
{
counter++;
}
return 0;
int x = 人;
整数计数器 = 0;
while(x != 计数器)
{
计数器++;
}
返回0;
回答by rOhAn703
Just use:
只需使用:
do
{
//enter code here
} while ( !condition );
So what this does is, it moves your 'check for condition' part to the end, since the while
is at the end. So it only checks the condition after running the code, just like how you want it
所以它所做的是,它将您的“检查条件”部分移到最后,因为while
是在最后。所以它只在运行代码后检查条件,就像你想要的那样
回答by Gilles Page
Repeat is supposed to be a simple loop n times loop... a conditionless version of a loop.
重复应该是一个简单的循环 n 次循环......循环的无条件版本。
#define repeat(n) for (int i = 0; i < n; i++)
repeat(10) {
//do stuff
}
you can also also add an extra barce to isolate the i variable even more
您还可以添加额外的 barce 以进一步隔离 i 变量
#define repeat(n) { for (int i = 0; i < n; i++)
#define endrepeat }
repeat(10) {
//do stuff
} endrepeat;
[edit] Someone posted a concern about passing a something other than a value, such as an expression. just change to loop to run backwards, causing the expression to be evaluated only once
[编辑] 有人发布了一个关于传递值以外的东西的问题,比如一个表达式。只需更改为循环向后运行,导致表达式仅计算一次
#define repeat(n) { for (int i = (n); i > 0; --i)