2017-03-11 46 views
-1

我已經試過在這裏查找這裏,仍然沒有找到我正在尋找的確切解決方案。數學不正確地出來。平均數字出來incorct

 //Local Constants 
     int count = 0;   //Used to track the number of grades entered by the user 

     //Local Variables 
     double currentGrade = 0; //User's current grade inputed 
     double numberGrades;  //Total number of grades to be entered 
     double totalGrade = 0;  //Total of all grades 
     double gradeAverage;  //Average of all grades 

     //Main Function 
     //Ask the user for the amount of grades they would like to enter 
     System.out.print ("How many grades would you like to enter? "); 
     numberGrades = scan.nextInt(); 

     //If the user asks to enter 0 numbers, output an error 
     while (numberGrades <= 0){ 
      System.out.print ("Please enter a valid number! "); 
     numberGrades = scan.nextInt(); 
     } 
     //Add the grades together as they are input by the user 
     while (count < numberGrades){ 
      totalGrade += currentGrade; 
      System.out.print ("Please enter your next grade: "); 
      currentGrade = scan.nextInt(); 
     count++; 
     } 
     //Calculate and output the average to the user 
     gradeAverage = (totalGrade/numberGrades); 
     System.out.print ("\n"); 
     System.out.print ("The average of all grades is: " + gradeAverage); 
    } 

}

認爲這是固定的,但是當我運行它,我仍然得到同樣的問題。我試過的例子是輸入3個數字,每個數字是50.平均結果是33.0。我運行了調試器,一旦輸入第一個數字,它就會一直給我提供錯誤。 count,totalGrade和currentGrade都顯示爲錯誤。不知道如何解決它。

+1

歡迎堆棧溢出!它看起來像你需要學習使用調試器。請幫助一些[互補調試技術](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之後仍然有問題,請隨時返回更多詳情。 –

+0

只需調試你的代碼,那麼你可能會注意到爲什麼你的程序實際上並不關心你最後的輸入。 – Tom

+0

@JoeBurkhart兩件事:1)你錯過了一個成績(最後一個); 2)你正在使用整數除法。 –

回答

0

在獲取輸入之前,您正在做這筆總和。之後你應該做。

替換您while環路與以下變化:

 while (count < numberGrades){ 

      System.out.print ("Please enter your next grade: "); 
      currentGrade = scan.nextInt(); 
      totalGrade += currentGrade; 
     count++; 
     } 
+0

哇。謝謝。當它看起來很簡單時,我只是完全忽略了幾小時後試圖移動其他所有東西的代碼。 –