首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 計算多位學生總分時避免累加錯誤的關鍵步驟

     編輯:程式設計綜合問答

問題場景

初學者撰寫 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]);
}

總結

「第二個人的成績總是和第一個相加」是典型的迴圈變數未重置錯誤。將累加變數移入迴圈區域或在每次迴圈結束時歸零,即可確保每位學生總分獨立計算。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved