Functions
Cambridge Pseudocode Lesson 13 2:02 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A function works something out and hands the answer back.
函数算出一个结果,然后把答案交回去。
Two words do that, and they are easy to mix up because they differ by one letter.
有两个词负责这件事,而它们只差一个字母,很容易混。
RETURNS, with an S, appears in the header and states the TYPE of the answer.
带 S 的 RETURNS 出现在头部,声明答案的"类型"。
RETURN, without one, appears in the body and sends the actual value.
不带 S 的 RETURN 出现在函数体里,送出实际的"值"。
Six goes in, thirty-six comes out.
6 进去,36 出来。
Because a function call has a value, it can go anywhere a value can go: stored into a variable, or written straight into a bigger expression.
因为函数调用本身就是一个值, 所以它可以出现在任何能放一个值的地方: 存进一个变量,或者直接写在一个更大的表达式里。
Read that second line the way the computer does — Square of four becomes sixteen first, and then the rest of the line carries on as ordinary arithmetic.
按计算机的读法去读第二行—— Square(4) 先变成 16, 然后这一行剩下的部分就按普通算术继续算。
A function can return a BOOLEAN, and that is the most useful kind in this course, because the answer can go straight into an IF.
函数可以返回一个 BOOLEAN, 而这在这门课里是最有用的一种,因为那个答案可以直接放进 IF 里。
Look carefully at the body: N greater than nought is already TRUE or FALSE, so it is returned directly — no IF needed inside the function.
仔细看函数体:N > 0 本身就已经是 TRUE 或 FALSE, 所以它被直接返回——函数里面不需要 IF。
Writing IF then return TRUE else return FALSE says the same thing twice.
写成"IF 就返回 TRUE,ELSE 就返回 FALSE", 等于把同一件事说了两遍。
And the question the exam asks in words: procedure or function?
而考卷会直接用文字问的那个问题:过程还是函数?
A procedure does a job — data goes in and nothing comes back, so you CALL it on its own line.
过程做一件事——数据进去,没有东西出来, 所以你在单独的一行上 CALL 它。
A function works something out and a value comes back, so its call sits inside something bigger.
函数算出一个东西,有一个值出来, 所以它的调用坐在某个更大的东西里面。
The test is simple: if the answer is used later in the program, write a function.
判断很简单:如果那个答案在程序后面还要用,就写函数。
Four things to take with you.
带走四点。
One: RETURNS in the header states the type it gives back.
第一:头部的 RETURNS 声明它交回的类型。
Two: RETURN in the body sends the value.
第二:函数体里的 RETURN 送出那个值。
Three: a function call can sit inside an expression.
第三:函数调用可以坐在一个表达式里面。
Four: a procedure does a job, and a function returns a value.
第四:过程做一件事,而函数返回一个值。
Now do the three tasks.
现在去做那三道题。