Selection: IF · 选择:IF
IF makes a decision
- Selection chooses what to do, based on a test.
IFruns itsTHENblock only when the test isTRUE.- The block ends at
ENDIF.
IF 做一个决定
- 选择(selection)根据一个测试来决定做什么。
IF只有在测试为TRUE时才运行它的THEN代码块。- 代码块以
ENDIF结束。
DECLARE Age : INTEGER
Age ← 20
IF Age >= 18
THEN
OUTPUT "You may vote"
ENDIF
IF ... ELSE
ELSEgives the path to take when the test isFALSE.- Exactly one of the two blocks runs.
IF ... ELSE
ELSE给出测试为FALSE时要走的那条路。- 两个代码块里恰好运行一个。
DECLARE Mark : INTEGER
Mark ← 72
IF Mark >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
TRUE or FALSE — which block runs? · TRUE 还是 FALSE —— 哪个块运行?
IF runs its THEN block when the test is TRUE; ELSE covers every other case. · 测试为 TRUE 时运行 THEN 块;ELSE 处理其余所有情况。
Comparison operators
=equal to,<>not equal to.<><=>=compare sizes.
比较运算符
=等于,<>不等于。<><=>=比较大小。
DECLARE N : INTEGER
N ← 7
IF MOD(N, 2) = 0
THEN
OUTPUT "even"
ELSE
OUTPUT "odd"
ENDIF
Watch out
- In a test,
=means "is equal to". (The arrow←is for storing a value.) - Don't forget
THENafter the test andENDIFto close the block.
注意
- 在测试里,
=表示“等于”。(箭头←是用来存值的。) - 别忘了测试后面的
THEN,以及用ENDIF关闭代码块。
Common mistakes
- Write
IF ... THEN ... ELSE ... ENDIF— do not forgetENDIF. - Compare with
=in pseudocode conditions.
常见错误
- 写
IF ... THEN ... ELSE ... ENDIF——别忘了ENDIF。 - 伪代码条件里用
=比较。
Now you try
- Read the input, then choose with
IF ... ELSE ... ENDIF. - Press Check answer to test it.
现在轮到你
- 读取输入,然后用
IF ... ELSE ... ENDIF选择。 - 按检查答案来测试它。
Read an INTEGER N. If it is greater than 0, output positive, otherwise output not positive. For input 5, output positive. · 读取一个 INTEGER N。如果它大于 0,输出 positive,否则输出 not positive。当输入为 5 时,输出 positive。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read a Mark. Output Pass if it is 50 or more, otherwise Fail. For input 40, output Fail. · 读取一个 Mark。如果它在 50 及以上,输出 Pass,否则输出 Fail。当输入为 40 时,输出 Fail。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read an INTEGER N. Output even if N MOD 2 = 0, otherwise odd. For input 8, output even. · 读取一个 INTEGER N。如果 N MOD 2 = 0 就输出 even,否则输出 odd。当输入为 8 时,输出 even。
Click Run to see the output here. · 点击“运行”查看此处输出。