1

I'm pretty new to arrays and am trying to create a simple program that calculates the average of 5 numbers. However, when the average is calculated, it always has a decimal point of 0 rather than what it should be, but I'm not sure why.. For example, if I type in 4, 4, 4, 4, 3, it displays 3.0 as the average rather than 3.8. Please help!

        int[] boxes = new int[5];

        for (int i = 1 ; i <= 5 ; i++)
        {
            System.out.print("Enter number " + i + " > ");
            int n = Integer.parseInt(kb.nextLine());

            boxes[i-1] = n;
        }

        double mean = ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5;

        System.out.println("The average of those five numbers is: " + mean);

Thank you!! :)

4 Answers4

1

it is because the operation is done with integers , change your 5 to 5.0

Stéphane
  • 867
  • 4
  • 7
0

I cannot answer you the specifics but there is a huge topic in java called type casting. I reckon, you read it. This is a good puzzle for you to solve yourself. Reminds me of my past :)

KameshG
  • 43
  • 8
0

Fast fix: change 5 -> 5.0D.

Why? Let's look at dividing process more detail:

  1. You get sum from all numbers: ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ), result -> int.
  2. You divide sum(int type) / 5(int type) = result also int type 3.8 -> 3.
  3. Last one its autocast int -> double.

That's why you get what you see.

EnjoyLife
  • 3
  • 2
  • 5
0

Solution 1 : - You can use 5.0 instead of 5 to have a double division.like that:

 double mean = ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5.0;

Solution 2 : - You can use a double cast of your sum like that:

 double mean = (double)( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5;

To improve your answer:

  • You can use int n=kb.nextInt(); instead of int n = Integer.parseInt(kb.nextLine());

  • You can count the sum in for loop like that:

    int[] boxes = new int[5];
    int sum=0;
    for (int i = 1 ; i <= 5 ; i++)
    {
    System.out.print("Enter number " + i + " > ");
    int n=kb.nextInt();
    boxes[i-1] = n;
    sum +=boxes[i-1];
    }
    
    double mean = sum / 5.0;
    System.out.println("The average of those five numbers is: " + mean);
    
Mourad BENKDOUR
  • 879
  • 2
  • 9
  • 11