Can't use double, can't use int, what do I use to stop the rounding? (Java)

62 views Asked by At

I am incredibly new to java and this is the description for a lab I currently have:

Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the max and average. A negative integer ends the input and is not included in the statistics. Assume the input contains at least one non-negative integer.

Output the average with two digits after the decimal point followed by a newline, which can be achieved as follows:

System.out.printf("%.2f\n", average);

Ex: When the input is:

15 20 0 3 -1

the output is:

20 9.50

This is my code:

      int count = 0;
      int sumNums = 0;
      int totalSumNums = 0;
      double average = 0;
      int bigNumber = -1;
      
      sumNums = scnr.nextInt();
      while (sumNums >= 0) {
         if (sumNums > bigNumber) {
            bigNumber = sumNums;
         }
         totalSumNums = totalSumNums + sumNums;
         count = count + 1;
         sumNums = scnr.nextInt();
      }
         average = totalSumNums / count;
      System.out.print(bigNumber + " ");
      System.out.printf("%.2f\n", average);

Mostly it works, but I am running into problems with the last line. If I use double, the number rounds. For example, if my input is: 2 3 -1, then my output is 3 2.00 instead of 3 2.50. I tried int, and that did not work at all (and that is the only other number thingy I know). I desperately cannot figure this out and I also really need to know this for a project that is due soon. Please help!!!

Edit: I am an idiot. All I had to do was change the line: average = totalSumNums / count; to average = (double)totalSumNums / count;

1

There are 1 answers

0
vbat On

When you divide two integers in Java, the result is always an integer. Try:

double average = 0.0;

and try to cast the average variable:

average = (double) totalSumNums / count;