Selection: CASE · 选择:CASE
CASE chooses among values
CASE OFcompares one variable against several values.- It is tidier than many
IFs when each value gives a fixed result. - The block ends at
ENDCASE.
CASE 在多个值之间选择
CASE OF把一个变量和好几个值比较。- 当每个值都给出一个固定结果时,它比许多
IF更整洁。 - 代码块以
ENDCASE结束。
DECLARE Grade : INTEGER
Grade ← 2
CASE OF Grade
1 : OUTPUT "Gold"
2 : OUTPUT "Silver"
3 : OUTPUT "Bronze"
ENDCASE
OTHERWISE catches the rest
OTHERWISEruns when no value matched.- Put it last, just before
ENDCASE.
OTHERWISE 兜住其余情况
- 当没有任何值匹配时,运行
OTHERWISE。 - 把它放在最后,就在
ENDCASE之前。
DECLARE Day : INTEGER
Day ← 1
CASE OF Day
1 : OUTPUT "Monday"
2 : OUTPUT "Tuesday"
OTHERWISE OUTPUT "Another day"
ENDCASE
Watch out
- Each branch is written
value : result. The colon:is required. CASEtests equality with set values — useIFfor ranges likeMark >= 50.
注意
- 每个分支写作
值 : 结果。冒号:是必需的。 CASE用固定的值做相等判断 —— 范围(如Mark >= 50)要用IF。
Common mistakes
CASE OF ... OTHERWISE ... ENDCASE;OTHERWISEcatches the rest.- Use CASE when you compare one variable against many values.
常见错误
CASE OF ... OTHERWISE ... ENDCASE;OTHERWISE处理其余情况。- 当把一个变量和多个值比较时用 CASE。
Now you try
- Read the input, then choose with
CASE OF ... ENDCASE. - Press Check answer to test it.
现在轮到你
- 读取输入,然后用
CASE OF ... ENDCASE选择。 - 按检查答案来测试它。
Read a Place (an INTEGER). Output Gold for 1, Silver for 2, Bronze for 3, and No medal for anything else. For input 2, output Silver. · 读取一个 Place(INTEGER)。1 输出 Gold,2 输出 Silver,3 输出 Bronze,其他输出 No medal。当输入为 2 时,输出 Silver。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read a CHAR G. Output Excellent for A, Good for B, OK for C, and Try again otherwise. For input B, output Good. · 读取一个 CHAR G。A 输出 Excellent,B 输出 Good,C 输出 OK,其他输出 Try again。当输入为 B 时,输出 Good。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read an INTEGER N. Output small for 1, medium for 2, and large for anything else. For input 9, output large. · 读取一个 INTEGER N。1 输出 small,2 输出 medium,其他输出 large。当输入为 9 时,输出 large。
Click Run to see the output here. · 点击“运行”查看此处输出。