0

I am practicing a question: Type several numbers and stops while you type 0. Print out the maximum, minimum and average of the numbers you type.

Following is my code, and I was stuck in the calculation of average. For example: when I type: 2 5 7 -1 0 the outcome is :

Type some numbers, and type 0 to end the calculattion: 
2 5 7 -1 0
The numbers you type are: 
2 5 7 -1 
Sum is: 13
There are 4 numbers
The Max number is : 7
The minimum number is : -1
Average is : 3.0

However, the Average should be 3.25. I've already made the variable avg in double type, why my output is still 3.0 rather than 3.25?

Thanks!!

public class Max_Min_Avg {


public static void main(String[] args) {
    System.out.println("Type some numbers, and type 0 to end the calculattion: ");
    Scanner scanner = new Scanner(System.in);
    int numbs = scanner.nextInt();
    int count =0;
    int sum =0;
    int max = 0;
    int min=0;
    System.out.println("The numbers you type are: ");
    while(numbs!=0) {
        System.out.print(numbs + " ");
        sum += numbs;
        count ++;
        numbs = scanner.nextInt();
        if(numbs>max) {
            max = numbs;
        }
        if(numbs<min) {
            min = numbs;
        }
    }
    while(numbs ==0) {
        break;

    }

    System.out.println();
    double avg = (sum/count);
    System.out.println("Sum is: "+ sum);
    System.out.println("There are "+ count + " numbers");
    System.out.println("The Max number is : " + max );
    System.out.println("The minimum number is : " + min);
    System.out.println("Average is : " + avg);

}
Shin Yu Wu
  • 1,129
  • 4
  • 14
  • 23

1 Answers1

0

This is the issue of integer division .sum/count is calculated as int since sum and count is of type int. You can solve this by implicit casting.

Try :-

double avg = sum*1.0/count;   // implicit casting.

Output :-

Type some numbers, and type 0 to end the calculattion: 
2 5 7 -1 0
The numbers you type are: 
2 5 7 -1 
Sum is: 13
There are 4 numbers
The Max number is : 7
The minimum number is : -1
Average is : 3.25
anoopknr
  • 3,177
  • 2
  • 23
  • 33