Rexx 编程/Rexx 指南/条件循环
外观
条件循环测试循环周围的条件,并在条件为真时重复执行一组指令。条件循环的类型包括 while 循环、until 循环和 repeat 循环。
While 循环是一种条件循环,它在条件为真时重复执行一组指令。while 语句用作 do 和 end 结构的句法组件,以生成 while 循环。
l = 0
do while l <= 10
say l
l = l + 1
end
Until 循环是一种条件循环,它在条件为真时重复执行一组指令。在 Rexx 中,until 语句与 do 和 end 结构一起使用以生成 until 循环。
l = 1;
do until l > 10
say l
l = l + 1
end
Repeat 循环是一种 [条件循环],它在条件为真时重复执行一组 [代码块] 指令。[do] 语句与 [until] 句法组件一起使用以生成 repeat 循环。
attempts = 1
do until attempts==10
say "Knock! Knock!"
attempts = attempts + 1
end
请注意,与 [while] 循环不同,在 repeat 循环中,[条件] 在 [循环] 中的 [代码块] 之后进行评估,即使它在开头写着。这意味着 repeat 循环中的代码块将始终至少运行一次。
/* This snippet asks the user their age and tries again if their answer is negative. */ /* The question will always be asked at least once. */ do until age >= 0 say "How old are you?" age = LineIn() if age < 0 then say "Your age cannot be negative." end
如果使用 [do] 和 [while] 组件而不是 [do] 和 [until],则循环将表现为 [while] 循环,条件在循环开始时进行评估。如果表达式计算结果为布尔 [false] 值,则这可能会导致循环根本不执行。
/* This snippet lets the user enter a number to start a countdown to lift off. */ /* If the user enters a negative number, there won't be a countdown at all. */ say "Where should I start the countdown?" number = LineIn() do while number > 0 say number number = number - 1 end say "Lift off!"