R 中的 do-while 循环
我想知道如何编写 do-while 风格的循环?
我发现这篇文章:
您可以使用repeat{}并使用if()和检查任何地方的条件 使用“break”控制字退出循环。
我不确定这到底是什么意思。如果您理解和/或您有不同的解决方案,有人可以详细说明吗?
I was wondering about how to write do-while-style loop?
I found this post:
you can use repeat{} and check conditions whereever using if() and
exit the loop with the "break" control word.
I am not sure what it exactly means. Can someone please elaborate if you understand it and/or if you have a different solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
注意到用户 42- 的完美方法{
* "do while" = "重复直到没有"
* 代码等价:
} 没有得到其他人足够的重视,我将通过一个具体的例子来强调并提出他的方法。如果不否定 do-while 中的条件(通过
!
或取反),则根据代码的过程,会出现扭曲的情况(1. 值持久性 2. 无限循环)。在高斯中:
在 R 中:
我仍然坚持认为,如果没有 do-while 中的条件否定,Salcedo 的答案是错误的。可以通过删除上面代码中的否定符号来检查这一点。
Noticing that user 42-'s perfect approach {
* "do while" = "repeat until not"
* The code equivalence:
} did not receive enough attention from the others, I'll emphasize and bring forward his approach via a concrete example. If one does not negate the condition in do-while (via
!
or by taking negation), then distorted situations (1. value persistence 2. infinite loop) exist depending on the course of the code.In Gauss:
In R:
I still insist that without the negation of the condition in do-while, Salcedo's answer is wrong. One can check this via removing negation symbol in the above code.
在其他答案的基础上,我想分享一个使用 while 循环构造来实现 do-while 行为的示例。通过在 while 条件中使用一个简单的布尔变量(初始化为 TRUE),然后在 if 语句中检查我们的实际条件。还可以在 if 语句中使用 break 关键字来代替 continue <- FALSE (可能更有效)。
Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).
请参阅
?Control
或 R 语言定义:因此,
do_while
在R中不作为单独的构造存在,但您可以通过以下方式伪造它:如果您想查看帮助页面,则无法键入
?while
或?repeat
在控制台,但需要使用?'repeat'
或?'while'
。所有的“控制结构”,包括if
都在同一页上,并且都需要在“?”之后引用字符。因此解释器不会将它们视为不完整的代码并给您一个延续“+”。See
?Control
or the R Language Definition:So
do_while
does not exist as a separate construct in R, but you can fake it with:If you want to see the help page you cannot type
?while
or?repeat
at the console but rather need to use?'repeat'
or?'while'
. All the "control-constructs" includingif
are on the same page and all need character quoting after the "?" so the interpreter doesn't see them as incomplete code and give you a continuation "+".非常不言自明。
或者类似的事情我会想。要获得 do while 循环的效果,只需检查语句组末尾的条件即可。
Pretty self explanatory.
Or something like that I would think. To get the effect of the do while loop, simply check for your condition at the end of the group of statements.