平均数字出现了

时间:2017-03-11 13:46:38

标签: java

我已经尝试过在这里查看,但仍未找到我正在寻找的确切解决方案。数学运算不正确。

       //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 个答案:

答案 0 :(得分:0)

在获得输入之前,你正在做总和。你应该在那之后再做。

使用以下更改替换while循环:

        while (count < numberGrades){

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