輸入一個整數分數(0-100),輸出對應等級:
多組測試數據,EOF 結束。
#include <stdio.h>
int main(void) {
int score;
while (scanf("%d", &score) != EOF) {
if (score >= 0 && score < 60)
printf("E\n");
else if (score >= 60 && score < 70)
printf("D\n");
else if (score >= 70 && score < 80)
printf("C\n");
else if (score >= 80 && score < 90)
printf("B\n");
else if (score >= 90 && score <= 100)
printf("A\n");
else
printf("Score is error!\n");
}
return 0;
}
原始代碼存在多餘的 `else` 和格式混亂問題。優化後:
| 輸入 | 輸出 | 說明 |
|---|---|---|
| 95 | A | 正常範圍 |
| 90 | A | 邊界值 |
| 89 | B | 邊界值 |
| 60 | D | 及格線 |
| 59 | E | 不及格 |
| -1 | Score is error! | 非法輸入 |
| 101 | Score is error! | 超出範圍 |
因 switch 不支援區間判斷,可結合除法技巧:
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:
if (score >= 0) printf("E\n");
else printf("Score is error!\n");
}
但 if-else 版本可讀性更好,推薦使用。