C语言实现分数等级评定:Switch语句和if语句对比
C语言实现分数等级评定:Switch语句和if语句对比
本文将使用两种不同的选择结构,Switch语句和if语句,用C语言编写代码,实现输入百分制分数,输出相应等级(A, B, C, D, E)的功能,并比较两种方法的优劣。
使用Switch语句
#include <stdio.h>
int main() {
int score;
printf("请输入一个百分制的分数:");
scanf("%d", &score);
switch (score / 10) {
case 10:
case 9:
printf('A\n');
break;
case 8:
printf('B\n');
break;
case 7:
printf('C\n');
break;
case 6:
printf('D\n');
break;
default:
printf('E\n');
}
return 0;
}
使用if语句
#include <stdio.h>
int main() {
int score;
printf("请输入一个百分制的分数:");
scanf("%d", &score);
if (score >= 90) {
printf('A\n');
} else if (score >= 80) {
printf('B\n');
} else if (score >= 70) {
printf('C\n');
} else if (score >= 60) {
printf('D\n');
} else {
printf('E\n');
}
return 0;
}
两种方法的比较
- Switch语句更适合处理有限的、离散的数值情况,代码简洁清晰。
- if语句更适合处理连续的范围判断,灵活性较高。
在实际应用中,根据具体情况选择合适的结构,可以提高代码效率和可读性。
原文地址: https://www.cveoy.top/t/topic/kEgq 著作权归作者所有。请勿转载和采集!