0

So I think it is a very simple question but I stuck in the problem with the correct sum with my code. Here is the description of this:

Write a program that asks the user for input until the user inputs 0. After this, the program prints the average of the numbers. The number zero does not need to be counted to the average. You may assume that the user inputs at least one number.

import java.util.Scanner;

public class AverageOfNumbers {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int sum = 0;
        int count = 0;
        while (true) {
            System.out.println("Give a number: ");
            int num = Integer.valueOf(scanner.nextLine());
            if (num == 0) {
                break;
            }
            if (num != 0) {
                count = count + 1;
                sum += num;   
            }
        }
        System.out.println("Number of numbers: " + count);
        System.out.println("Sum of the numbers: " + sum);
        System.out.println("Average of the numbers: " + 1.0 * (sum/count));
    }
}

For example, if I entered 5 numbers: 5, 22 ,9, -2, 0. The result should be 8.5. But with my code the result is 8.0. Where did I get the problem? The sum part or the average part? Or the method I tried to get the 2 digit result? Thank you.

KomPr3ssoR
  • 13
  • 2

1 Answers1

-1

In your code, both sum and count are integers. As defined by the spec, "Next, a value must be chosen from the chosen value set to represent the quotient.", therefore dividing two integers still gives an integer, truncating the decimal part if necessary. Thus 8.5 becomes 8. you need to cast one of your numbers to a float (or a double) before you divide them: average = ((float)sum)/count. That way Java keeps the highest precision, the float and returns a deciamal value

NatMath
  • 78
  • 6
  • 3
    The "because" is a wrong conclusion. And please use `double` instead of `float`, it's more natural. – Roland Illig May 26 '20 at 23:53
  • Ok, thank you @RolandIllig This is my first answer, if you have any suggestion on how to improve the wording You're welcome to say so – NatMath May 27 '20 at 11:05
  • My main critique was about the "because". That word is wrong. Dividing two integers gives an integer [_because the language specification says so_](https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.17.2). Whether Java is or is not statically typed doesn't matter. – Roland Illig May 27 '20 at 19:20
  • Thank you @RolandIllig, I made the change – NatMath May 29 '20 at 11:59
  • The "Next" paragraph you cited is not applicable here. This is integer division, and you cited floating point division. In integer division, there is no infinity. – Roland Illig May 30 '20 at 05:21