while 循环
优质
小牛编辑
141浏览
2023-12-01
While循环一次又一次地执行相同的代码,直到满足停止条件。
语法 (Syntax)
在R中创建while循环的基本语法是 -
while (test_expression) {
statement
}
流程图 (Flow Diagram)

这里while循环的关键点是循环可能永远不会运行。 当测试条件并且结果为假时,将跳过循环体并且将执行while循环之后的第一个语句。
例子 (Example)
v <- c("Hello","while loop")
cnt <- 2
while (cnt < 7) {
print(v)
cnt = cnt + 1
}
编译并执行上述代码时,会产生以下结果 -
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"