Iteration: WHILE and REPEAT · 迭代:WHILE 与 REPEAT
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
WHILE tests first
- A pre-condition loop tests the condition, then maybe runs the body.
- If the condition is already
FALSE, the body never runs. - The block ends at
ENDWHILE.
中文
WHILE 先判断
- 前测试循环先判断条件,然后才可能运行循环体。
- 如果条件一开始就是
FALSE,循环体一次也不运行。 - 这一段在
ENDWHILE结束。
DECLARE N : INTEGER
N ← 3
WHILE N > 0
OUTPUT N
N ← N - 1
ENDWHILE
English
REPEAT runs, then tests
- A post-condition loop runs the body, then tests.
- The body runs at least once.
- The loop stops when the condition becomes
TRUE.
中文
REPEAT 先运行再判断
- 后测试循环先运行循环体,再判断。
- 循环体至少运行一次。
- 条件变成
TRUE时循环停止。
DECLARE N : INTEGER
N ← 0
REPEAT
N ← N + 1
OUTPUT N
UNTIL N = 3
English
Watch out
WHILEstops onFALSE.REPEATstops onTRUE. They are opposite tests.- Something inside a
WHILEmust change the condition, or the loop never ends.
中文
注意
WHILE在FALSE时停止。REPEAT在TRUE时停止。两种判断正好相反。WHILE里面必须有语句改变条件,否则循环不会结束。
English
Common mistakes
ENDWHILEcloses aWHILE.UNTILcloses aREPEAT.- A
REPEATthat should stop at 3 must updateNbefore the test.
中文
常见错误
ENDWHILE结束WHILE。UNTIL结束REPEAT。- 想在 3 停下来的
REPEAT,必须在判断之前更新N。
English
Now you try
- Write one
WHILEand oneREPEAT.
中文
现在你来试
- 写一个
WHILE和一个REPEAT。
Set · 集合 N to · 到 3. While N is greater than 0, output N and then subtract 1. · 把 N 设为 3。当 N 大于 0 时,输出 N,然后减去 1。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use REPEAT … UNTIL to output 1, 2 and 3. · 用 REPEAT … UNTIL 输出 1、2 和 3。
Click Run to see the output here. · 点击“运行”查看此处输出。