初學者撰寫 Java 程式計算多位學生的總分,發現第二位學生的總分會包含第一位學生的分數,導致結果錯誤。典型錯誤程式碼如下:
int bianliang = 0; // 累加變數
for (int i = 0; i < studentCount; i++) {
// 輸入各科成績並累加
bianliang += score1 + score2 + score3;
zhongfen[i] = bianliang; // 存入陣列
// 缺少重置 bianliang = 0;
}
累加變數 bianliang 未在每位學生迴圈開始時歸零,導致後續學生的總分包含前一位學生的分數。
在將總分存入陣列後,或在下一位學生迴圈開始前,將累加變數重設為 0:
for (int i = 0; i < studentCount; i++) {
int bianliang = 0; // 移到迴圈內部,每次自動歸零
// 輸入成績並累加
bianliang += score1 + score2 + score3;
zhongfen[i] = bianliang;
}
// 或在迴圈結束時重置
bianliang = 0;
totalScore 取代 bianliang,提升可讀性。Scanner sc = new Scanner(System.in);
System.out.print("學生人數:");
int n = sc.nextInt();
int[] zhongfen = new int[n];
for (int i = 0; i < n; i++) {
int total = 0; // 每位學生獨立累加
System.out.printf("第 %d 位學生 - 國文:", i + 1);
total += sc.nextInt();
System.out.print("數學:");
total += sc.nextInt();
System.out.print("英文:");
total += sc.nextInt();
zhongfen[i] = total;
System.out.printf("總分:%d\n", total);
}
// 輸出所有總分
for (int i = 0; i < n; i++) {
System.out.printf("學生 %d 總分:%d\n", i + 1, zhongfen[i]);
}
「第二個人的成績總是和第一個相加」是典型的迴圈變數未重置錯誤。將累加變數移入迴圈區域或在每次迴圈結束時歸零,即可確保每位學生總分獨立計算。