5.1 KiB
5.1 KiB
title | localeTitle |
---|---|
Golf Code | 高尔夫码 |
如果卡住,请记得使用**Read-Search-Ask
** 。尝试配对程序并编写自己的代码
问题说明:
在高尔夫比赛中,每个洞都具有标准意义,即高尔夫球手为了将球沉入洞中以完成比赛所期望的平均击球次数。根据你的笔画高出或低于标准杆的距离,有一个不同的昵称。
您的函数将通过par和stroke参数。您必须根据此表返回正确的字符串,该表按优先级顺序列出笔划;顶部(最高)到底部(最低):
笔画|返回
:--------- | :-------------
1 | “一杆进洞!”
<= par - 2 | “鹰”
par - 1 | “小鸟”
帕尔| “相提并论”
par + 1 | “柏忌”
par + 2 | “双柏忌” > = par + 3 | “回家!”
标准杆和笔画将始终为数字和正数。
- 更改下面的代码
// Only change code below this line
以上的代码// Only change code below this line
以上的// Only change code above this line
。 - 确保您正在编辑
golfScore
功能的内部。 - 您必须使函数返回与表中所示的完全相同的字符串,具体取决于传递给函数的参数par和笔画的值。
提示:1
+number -number
可用于增加或减少条件中的参数。
现在尝试解决问题
提示:2
您可以使用if / else if
chains在不同的场景中返回不同的值。
现在尝试解决问题
提示:3
根据表的优先级顺序控制函数流 - 顶部(最高)到底部(最低)以返回匹配的字符串值。
现在尝试解决问题
扰流警报!
提前解决!
基本代码解决方案
function golfScore(par, strokes) {
// Only change code below this line
if (strokes == 1){
return "Hole-in-one!";
} else if (strokes <= par -2){
return "Eagle";
} else if (strokes == par -1) {
return "Birdie";
} else if (strokes == par) {
return "Par";
} else if (strokes == par +1) {
return "Bogey";
} else if (strokes == par +2) {
return "Double Bogey";
} else {
return "Go Home!";
}
// Only change code above this line
}
// Change these values to test
golfScore(5, 4);
代码说明:
- 比较参数par和stroke以返回适当的字符串值。
if / else if
chain用于流量控制。- 字符串“回家!”对于笔划大于或等于par + 3的每个条件都会返回。
替代代码解决方案
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
// Only change code below this line
if (strokes == 1){
return names[0];
}
else if (strokes <= par-2){
return names[1];
}
else if (strokes == par -1){
return names[2];
}
else if (strokes == par){
return names[3];
}
else if (strokes == par +1){
return names[4];
}
else if (strokes == par +2){
return names[5];
}
else {return names[6];}
// Only change code above this line
}
// Change these values to test
golfScore(5, 4);
·在repl.it运行
##代码说明 由于我们已经在变量names
定义了一个数组,我们可以利用它并将它用于使用索引的返回语句(例如: names[0] is the first one
)。这样,如果您需要更改特定结果,则不需要在函数内部查找它,它将位于数组的开头。