輸入正整數 n,再輸入 n 個百分制成績,統計 A(90-100)、B(80-89)、C(70-79)、D(60-69)、E(0-59) 五個等級的人數。
int a, b, c, d, e; // 只有聲明,無初始化
// ...
if (score >= 90) a++;
// ...
局部變量未初始化時值為隨機垃圾值,a++ 導致統計結果完全錯誤。
在聲明處或使用前顯式初始化為 0:
int a = 0, b = 0, c = 0, d = 0, e = 0;
// 或分開寫
a = b = c = d = e = 0;
#include <stdio.h>
int main() {
int n, score;
int a = 0, b = 0, c = 0, d = 0, e = 0;
printf("輸入學生人數: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("輸入第 %d 位學生成績: ", i + 1);
scanf("%d", &score);
if (score >= 90) a++;
else if (score >= 80) b++;
else if (score >= 70) c++;
else if (score >= 60) d++;
else e++;
}
printf("A: %d\nB: %d\nC: %d\nD: %d\nE: %d\n", a, b, c, d, e);
return 0;
}
else if 鏈,避免多重 if 重複判斷,提高效率。score 是否在 0-100 範圍內。