当我运行此代码并输入数字:1、2、3、4、5、6、7、8、9、10时,我的平均值为5.0,但我希望它显示为5.5?

时间:2019-09-28 03:27:00

标签: java netbeans

这是我的代码,用于计算奇数,偶数,最大值,最小值和范围。用户输入10个数字,该代码应计算所有内容。我遇到的问题是计算平均值。当我输入10个数字时,例如:1、2、3、4、5、6、7、8、9、10,我得到的平均值为5.0。但是,我该如何编写代码以使平均值为5.5,而不是使平均值四舍五入呢?

package javasumavgrange;
import java.util.Scanner;

public class JavaSumAvgRange {
   public static final int NUMBER_COUNT = 10;

   public static void main(String[] args) {
      int sumOfOddNumbers = 0;
      int sumOfEvenNumbers = 0;
      int sumOfAllNumbers = 0;
      int number;
      int minValue = 0;
      int maxValue = 0;
      int inputCounter = 1;
      double averageOfNumbers = 0.0;

      Scanner stdin = new Scanner(System.in);

      //INPUT: numbers
      while (inputCounter <= NUMBER_COUNT){
         System.out.print("Enter a number: ");
         number = stdin.nextInt();
         //process to detect even/odd numbers:
         if(number%2 == 1){
            sumOfOddNumbers += number;
         }
         else {
            sumOfEvenNumbers += number;
         }
         //process to detect total of all numbers
         sumOfAllNumbers += number;

         //determine the range (min, max) of inputs
         if( inputCounter ==1){
            minValue = number;
            maxValue = number;
         }
         else {
            if (number<minValue){
               minValue = number;
            }
            if(number > maxValue){
               maxValue = number;
            }
         }
         //keep count of how many numbers were entered
         inputCounter++;
      } // end of while loop

      // here I am calculating the average. When I put 10 numbers in, For example 1,2,3,4,5,6,7,8,9,10, Iget 5.0
      averageOfNumbers = sumOfAllNumbers/NUMBER_COUNT;

      //What I am trying to do is calculate the average to be 5.5 for those 10 numbers mentioned above.


      //OUPUT:
      System.out.println( );
      System.out.println("Sum of Odd Numbers: " + sumOfOddNumbers);
      System.out.println("Sum of Even Numbers: " + sumOfEvenNumbers);
      System.out.println("Sum of All Numbers: " + sumOfAllNumbers);
      System.out.println("The lowst value is: " + minValue);
      System.out.println("The highest value is: " + maxValue);
      System.out.println("The aveagr of the numbers is " + averageOfNumbers);
      System.out.println( );
   }
}

0 个答案:

没有答案