Functions · 函数
A FUNCTION returns a value
- A function works something out and hands back a value with
RETURN. RETURNS(in the header) states the type of value it gives back.
FUNCTION 返回一个值
- 函数(function)算出一个结果,用
RETURN把值交回去。 RETURNS(在函数头里)说明它返回的值的类型。
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION
OUTPUT Square(6) // → 36
Run, then RETURN a value · 运行,然后 RETURN 一个值
A FUNCTION runs its steps, then RETURNs a value you can use in an expression. · FUNCTION 运行它的步骤,然后 RETURN 一个你能在表达式里使用的值。
Use the returned value
- Call a function inside an expression, or store its result in a variable.
使用返回的值
- 在表达式里调用函数,或把它的结果存进一个变量。
FUNCTION Square(Number : INTEGER) RETURNS INTEGER
RETURN Number * Number
ENDFUNCTION
DECLARE Answer : INTEGER
Answer ← Square(4)
OUTPUT Answer + 1 // → 17
A function can return a Boolean
- The result can be a
BOOLEAN— handy for a yes/no test.
函数可以返回布尔值
- 结果可以是
BOOLEAN—— 很适合做一个是/否的判断。
FUNCTION IsPositive(N : INTEGER) RETURNS BOOLEAN
RETURN N > 0
ENDFUNCTION
OUTPUT IsPositive(5) // → TRUE
Watch out
- A procedure does something; a function returns a value you then use.
- Every path through a function must reach a
RETURN.
注意
- 过程(procedure)做某件事;函数(function)返回一个你随后会用到的值。
- 函数里的每一条路径都必须走到一个
RETURN。
Common mistakes
FUNCTION Name(...) RETURNS TYPE ... RETURN Value ... ENDFUNCTION.- A function must
RETURNa value.
常见错误
FUNCTION Name(...) RETURNS TYPE ... RETURN Value ... ENDFUNCTION。- 函数必须
RETURN一个值。
Now you try
- Define a function with
RETURNSandRETURN. - Press Check answer to test it.
现在轮到你
- 用
RETURNS和RETURN定义一个函数。 - 按检查答案来测试它。
Define FUNCTION Square(N : INTEGER) RETURNS INTEGER that returns N × N, then output Square(5) (it is 25). · 定义 FUNCTION Square(N : INTEGER) RETURNS INTEGER,返回 N × N,然后输出 Square(5)(是 25)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Define FUNCTION Add(a : INTEGER, b : INTEGER) RETURNS INTEGER that returns a + b, then output Add(3, 4) (it is 7). · 定义 FUNCTION Add(a : INTEGER, b : INTEGER) RETURNS INTEGER,返回 a + b,然后输出 Add(3, 4)(是 7)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Define FUNCTION IsEven(N : INTEGER) RETURNS BOOLEAN that returns TRUE when N is even, then output IsEven(8) (it is TRUE). · 定义 FUNCTION IsEven(N : INTEGER) RETURNS BOOLEAN,当 N 是偶数时返回 TRUE,然后输出 IsEven(8)(是 TRUE)。
Click Run to see the output here. · 点击“运行”查看此处输出。