Night 13: Your pet answers
你已使用 Python 或伪代码完成过这个夜间练习,两种语言均计入完成记录。你可以再次练习。
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Tonight: your pet answers
- Until now, your pet's tricks did something: they output text.
- Tonight your pet answers. A function gives a value back.
- You will learn one thing:
FUNCTIONwithRETURN.
Words for tonight
| Word | Meaning |
|---|---|
| function | a named block of code that gives a value back |
| return | give a value back to the place where it is used |
| result | the value a function gives back |
English
Give a value back
- The first line says the type that comes back:
RETURNS INTEGER. RETURNsends the value back. The call becomes that value.
FUNCTION Double(N : INTEGER) RETURNS INTEGER
RETURN N * 2
ENDFUNCTION
DECLARE Answer : INTEGER
Answer ← Double(4)
OUTPUT Answer
OUTPUT Double(10) + 1
Double(4)becomes8.Double(10) + 1becomes20 + 1.

English
Procedure or function?
PROCEDURE |
FUNCTION |
|---|---|
| does a job | gives a value back |
used with CALL Wave() |
used in an expression: OUTPUT Double(4) |
no RETURNS |
RETURNS and a type |
- Never write
CALL Double(4), and never use a procedure inside anOUTPUT.
English
Answer a yes/no question
Food < 3is alreadyTRUEorFALSE. A function can return it.
FUNCTION IsHungry(Food : INTEGER) RETURNS BOOLEAN
RETURN Food < 3
ENDFUNCTION
IF IsHungry(1) THEN
OUTPUT "Feed me!"
ENDIF
English
RETURN ends the function
- When
RETURNruns, the function stops at once.
FUNCTION Mood(Energy : INTEGER) RETURNS STRING
IF Energy > 7 THEN
RETURN "happy"
ENDIF
RETURN "sleepy"
ENDFUNCTION
OUTPUT Mood(9)
OUTPUT Mood(2)
- Now let your pet answer in the tasks!
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write a function Double(N : INTEGER) RETURNS INTEGER. It 返回值 N times 2. Then output Double(4). The output is 8.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write IsHungry(Food : INTEGER) RETURNS BOOLEAN. It returns TRUE when Food is less than 3, and FALSE otherwise.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write Mood(Energy : INTEGER) RETURNS STRING. It returns "happy" when energy is more than 7, "ok" when it is more than 3, and "sleepy" otherwise.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write Bigger(A : INTEGER, B : INTEGER) RETURNS INTEGER. It returns the bigger of the two numbers. If they are the same, return either one.
点击“运行”查看此处输出。