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.