优化这个代码function getGrade(score) if score >= 90 and score <= 100 then return "A" elseif score >= 80 and score < 90 then return "B" elseif score >= 70 and score < 80 then return "C" elseif score >= 60 and score < 70 then return "D" elseif score >= 0 and score < 60 then return "E" else return "Invalid score" end end score = io.read("*n") grade = getGrade(score) print(grade)
时间: 2023-04-10 20:04:07 浏览: 47
这段代码可以进行一些简单的优化,比如可以将 if-elseif 结构改为一个 switch-case 结构,这样可以使代码更加简洁易懂。另外,可以添加一些错误处理的代码,比如当输入的分数不在 0-100 范围内时,给出相应的错误提示。以下是优化后的代码:
function getGrade(score)
local grade
if score < 0 or score > 100 then
grade = "Invalid score"
else
local score_range = math.floor(score / 10)
case = {
[9] = "A",
[8] = "B",
[7] = "C",
[6] = "D",
[5] = "E",
[4] = "E",
[3] = "E",
[2] = "E",
[1] = "E",
[0] = "E",
}
grade = case[score_range]
end
return grade
end
score = io.read("*n")
grade = getGrade(score)
print(grade)
相关问题
编写一个函数getGrade(score),score是分数。90~100返回A,80~89返回B,60-79返回C,0~60返回D,其他返回error。
好的,我可以为您编写这个函数。以下是 Python 语言的实现代码:
```python
def getGrade(score):
if score >= 90 and score <= 100:
return 'A'
elif score >= 80 and score <= 89:
return 'B'
elif score >= 60 and score <= 79:
return 'C'
elif score >= 0 and score <= 60:
return 'D'
else:
return 'error'
```
这个函数接收一个参数 score,根据分数的范围返回不同的等级。如果分数不在指定范围内,则返回 "error"。您可以根据需要调用这个函数,比如:
```python
print(getGrade(85)) # 输出 B
```
用c语言编程,判断分数对应的等级应通过函数实现,优秀、良好、中等、及格、不及格分别用A、B、C、D、E表示 main函数中先要求用户输入分数,分数有效(>=0且<=100)时,调用函数确定并显示等级,然后通过goto语句转移到输入分数的语句继续处理。
下面是实现该功能的C语言代码:
```
#include <stdio.h>
char getGrade(int score);
int main() {
float score;
char grade;
input_score:
printf("请输入分数:");
scanf("%f", &score);
if (score < 0 || score > 100) {
printf("分数无效,请重新输入。\n");
goto input_score;
}
grade = getGrade(score);
printf("分数%.2f对应的等级为%c。\n", score, grade);
goto input_score;
return 0;
}
char getGrade(int score) {
if (score >= 90) {
return 'A';
} else if (score >= 80) {
return 'B';
} else if (score >= 70) {
return 'C';
} else if (score >= 60) {
return 'D';
} else {
return 'E';
}
}
```
首先在主函数中使用一个标签`input_score`,使程序可以跳转到输入分数的语句。然后在输入分数时,通过判断分数是否有效,如果无效则要求用户重新输入。接着调用`getGrade`函数获取分数对应的等级,并输出结果。最后通过`goto`语句回到输入分数的语句,实现程序的循环。`getGrade`函数通过分数的大小判断等级,并返回等级对应的字符。