1

I cannot seem to be able to get this code to properly average numbers. When i input 5 numbers that are 1 digit such as 9, 6, 2 etc. it gives me incorrect results, such as putting in five 2's, it will give me the answer '0.0'. Even when inputting numbers with two or more digits it rounds the number incorrectly. Its like its not even recognising it as being a double. I think i am missing something extremely obvious, haven't programmed in a while so wouldn't be surprised.

Here is the code:

    import java.util.*;

    public class LittleBoxes2
    {
        public static void main (String[] args)
        {
            Scanner input = new Scanner (System.in);
            int[] num;
            double avg;
            String cont = "Y";

            while(cont.equals("Y") || cont.equals("y"))
            {
                num = new int [5];

                for(int i = 1; i <= 5; i++)
                {
                    System.out.println("Enter number " + i + ".");
                    num[i - 1] = input.nextInt();
                }

                avg = num[0] / 5 + num[1] / 5 + num[2] / 5 + num[3] / 5 + num[4] / 5;

                System.out.println("The average number is: " + avg + ".");

                System.out.println("Do you want to continue? (Y/N)");
                input.nextLine();
                cont = input.nextLine();
            }
        }
    }
  • Try using the new Java 8 `Stream` API - most notable [`IntStream.summaryStatistics`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#summaryStatistics--). – Boris the Spider Nov 09 '14 at 21:12
  • `avg = num[0] / 5 + num[1] / 5 + num[2] / 5 + num[3] / 5 + num[4] / 5;` ... or in short and correct: `avg = (num[0] + num[1] + num[2] + num[3] + num[4]) / 5.0;` – Tom Nov 09 '14 at 21:22

1 Answers1

1

When both operands of / are integers, the division is integer division. You have:

avg = num[0] / 5 + num[1] / 5 + num[2] / 5 + num[3] / 5 + num[4] / 5;

This means, for example, 8 / 5 evaluates to 1, and 2 / 5 evaluates to 0. For your five 2's example this evaluates to:

= 2 / 5 + 2 / 5 + 2 / 5 + 2 / 5 + 2 / 5
= 0 + 0 + 0 + 0 + 0
= 0

You want, e.g.:

avg = num[0] / 5.0 + num[1] / 5.0 + num[2] / 5.0 + num[3] / 5.0 + num[4] / 5.0;

With that, one operand is a double, and so the num[n] integer operands are promoted to double, the division is floating-point division, and the result is a double.

Jason C
  • 38,729
  • 14
  • 126
  • 182