需要帮助找到平均值

时间:2014-10-07 20:15:23

标签: java

我似乎无法弄清楚如何根据用户输入的分数来计算平均分数。我也不能让它停止输出超过100或更少的输入0.有人能告诉我我做错了什么吗?感谢。

public static void main(String[] args) {


   Scanner scan = new Scanner(System.in);

   int sum = 0;
   int inputNumber;
   int numberExams;
   float averageScore;
   double max = 0; 
   double min = 101;      


   System.out.println("Enter the total number of exams you want a average");
   numberExams = scan.nextInt();

   System.out.println("Please enter " + numberExams + " numbers:");

   for(int i = 1; i<=numberExams ;i++){          
    inputNumber = scan.nextInt();
    sum = sum + inputNumber;
    System.out.println();

   if(inputNumber > max){
    max = inputNumber;
}
   if(inputNumber < min){
    min = inputNumber;
}
   if(inputNumber > -1 && inputNumber < 101){
    sum = sum + inputNumber;
}
   else{
    System.out.println("You entered a number that wasn't in the range of 0 to 100");
}
} 


    averageScore = sum / numberExams;

System.out.println( "The Max Exam Score is: " + max );
System.out.println( "The Minimum Exam Score is: " + min );    
System.out.println("The Average Exam Score is: " + averageScore );
}
}

2 个答案:

答案 0 :(得分:1)

在分配到minmax之前,您应首先检查您的范围。

这有效:

public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);

  int sum = 0;
  double averageScore;
  double max = 0;
  double min = 101;

  System.out.println("Enter the total number of exams you want a average");
  final int numberExams = scan.nextInt();

  System.out.println("Please enter " + numberExams + " numbers:");

  for (int i = 0; i < numberExams; ++i) {
    final int inputNumber = scan.nextInt();

    if (inputNumber >= 0 && inputNumber <= 100) {
      System.out.println();

      if (inputNumber > max) {
        max = inputNumber;
      }
      if (inputNumber < min) {
        min = inputNumber;
      }
      sum += inputNumber;
    }
    else {
      System.out.println("You entered a number that wasn't in the range of 0 to 100");
    }
  }

  averageScore = sum / numberExams;

  System.out.println("The Max Exam Score is: " + max);
  System.out.println("The Minimum Exam Score is: " + min);
  System.out.println("The Average Exam Score is: " + averageScore);
}

请注意,您仍有一个问题,即如果您收到无效输入,则您将计算错误的分数。你可以用几种不同的方式来处理。一种方法是在i区块内递减else

答案 1 :(得分:1)

您在sum = sum + inputNumber中执行了for-loop两次。

此外,您需要将int转换为double以计算平均值:

double average = ((double) sum) / numberExams;