Functions · 函数
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
A function returns one value
- A function is like a procedure, and it also hands one value back.
- The definition says the type of that value:
RETURNS INTEGER. RETURNsets the value. It is normally the last line of the function.
中文
函数返回一个值
- 函数和过程类似,并且还会交回一个值。
- 定义里写出这个值的类型:
RETURNS INTEGER。 RETURN设定这个值。它通常是函数的最后一行。
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION
OUTPUT Square(6)
English
Do not write CALL
- A function is used inside an expression, where its returned value is needed.
CALLis only for a procedure.- Parameters of a function are passed by value. The guide says not to use
BYREFon a function.
中文
不要写 CALL
- 函数用在表达式里,用在需要它的返回值的地方。
CALL只用于过程。- 函数的参数按值传递。指南说明不要在函数上使用
BYREF。
FUNCTION Max(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER
IF Number1 > Number2 THEN
RETURN Number1
ELSE
RETURN Number2
ENDIF
ENDFUNCTION
OUTPUT Max(10, 24)
English
Common mistakes
RETURNbelongs inside the function. Outside it, there is nothing to return to.- The call
Square(6)is not a complete statement on its own.OUTPUT Square(6)is.
中文
常见错误
RETURN写在函数里面。写在外面时,没有地方可以返回。Square(6)本身不是一条完整的语句。OUTPUT Square(6)才是。
English
Now you try
- Write a function and use its result in
OUTPUT.
中文
现在你来试
- 写一个函数,并在
OUTPUT里使用它的结果。
Write Square so that OUTPUT Square(6) prints 36. · 写 Square,使 OUTPUT Square(6) 打印 36。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write Max to return the larger of two integers. OUTPUT Max(10, 24) should print 24. · 写 Max,返回两个整数中较大的一个。OUTPUT Max(10, 24) 应打印 24。
Click Run to see the output here. · 点击“运行”查看此处输出。