輸入一個整數分數 a(多組測試,EOF 結束),輸出對應等級:
#include
int main(void) {
int a;
while (scanf("%d", &a) != EOF) {
if (a > -1 && a < 60)
printf("E\n");
else // ← 原代碼此處有雜亂字符 "www.2cto.com"
if (a > 59 && a < 70)
printf("D\n");
else
if (a > 69 && a < 80)
printf("C\n");
else
if (a > 79 && a < 90)
printf("B\n");
else
if (a > 80 && a < 101) // ← Bug: 80-89 歸 B,90-100 也進這裡
printf("A\n");
else
printf("Score is error!\n");
}
return 0;
}
elsewww.2cto.com 導致編譯錯誤。a > 80 && a < 101 覆蓋了 80-100,導致 90-100 輸出 A,但 80-89 本應輸出 B,邏輯衝突。if-else 缺乏大括號,可讀性極差,易出錯。
#include
int main(void) {
int score;
while (scanf("%d", &score) == 1) { // 更清晰的 EOF 判斷
if (score < 0 || score > 100) {
printf("Score is error!\n");
} else if (score < 60) {
printf("E\n");
} else if (score < 70) {
printf("D\n");
} else if (score < 80) {
printf("C\n");
} else if (score < 90) {
printf("B\n");
} else { // 90-100
printf("A\n");
}
}
return 0;
}
else if 鏈,前一條件不滿足隱含前條件反面,邊界清晰無重疊。{},防止後期維護引入 Bug。a → score。
const char *grade[] = {
"E", "E", "E", "E", "E", "E", // 0-5
"D", "D", "D", "D", // 6-9 (60-69)
"C", "C", "C", "C", // 10-13 (70-79)
"B", "B", "B", "B", // 14-17 (80-89)
"A", "A", "A", "A", "A", "A", "A", "A", "A", "A" // 18-27 (90-100)
};
int main() {
int score;
while (scanf("%d", &score) == 1) {
if (score < 0 || score > 100)
printf("Score is error!\n");
else
printf("%s\n", grade[score / 10]);
}
return 0;
}
適用於等級固定、性能敏感場景。
| 輸入 | 輸出 | 說明 |
|---|---|---|
| 59 | E | 及格線邊界 |
| 60 | D | |
| 89 | B | |
| 90 | A | 優秀線邊界 |
| 100 | A | 上限 |
| -1 | Score is error! | 下限越界 |
| 101 | Score is error! | 上限越界 |