If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

带返回值的过程

返回值的必要性

``````var score  = (numCorrect/30) * 100;
println(score);``````

``````function calcScore(numCorrect) {
var score  = (numCorrect/30) * 100;
return score;
}``````

``````var sallyScore = calcScore(27);
var wilburScore = calcScore(24);``````

``````println(calcScore(27));
println(calcScore(24));``````

``````println("Sally earned: " + calcScore(27));
println("Wilbur earned: " + calcScore(24));``````
📝 在以下网站查看类似代码: App Lab | Snap | Python
`calcScore()` 的调用总是会返回一个值，所以我们可以在 任何一个 需要使用数值的地方使用它。这种用法很常见！

``````var maxNum = Math.max(33, 100);
var firstName = "Harry Potter".substr(0, 5);
var yell = "im hungry".toUpperCase();```````

✏️ 下面的程序计算需要多少个”我“ 叠在一起才能达到特定高度，例如月球或自由女神像。更改它，以计算“你”的数量，并且加入另一个参照物结构，例如珠穆朗玛峰或太阳。
📝 在以下网站查看类似代码: App Lab | Snap | Python

当心程序提早返回

``````function calcLineSlope(x1, y1, x2, y2) {
var yDiff = y2 - y1;
var xDiff = x2 - x1;
return slope;
var slope = yDiff / xDiff;
}``````

``````function calcLineSlope(x1, y1, x2, y2) {
var yDiff = y2 - y1;
var xDiff = x2 - x1;
return slope;
}``````

``````function calcLineSlope(x1, y1, x2, y2) {
var yDiff = y2 - y1;
var xDiff = x2 - x1;
var slope = yDiff / xDiff;
return slope;
}``````
📝 在以下网站查看类似代码: App Lab | Snap | Python

用伪代码写的返回值

``````PROCEDURE name (parameter1, parameter2)
{
<instructions>
RETURN (expression)
}``````

``````PROCEDURE calcLineSlope (x1, y1, x2, y2)
{
yDiff ← y2 - y1
xDiff ← x2 - x1
slope ← yDiff / xDiff
RETURN slope
}

slope1 ← calcLineSlope(1, 2, 4, 5)
slope2 ← calcLineSlope(0, -1, 3, 10)``````
🙋🏽🙋🏻‍♀️🙋🏿‍♂️你对这个章节还有问题吗？我们会尽力回答— 请在下面提问框里留言！