Java Arena
Step 4 of 6

Division and casting

Dividing two int values gives an int: the part after the decimal point is simply dropped, not rounded.

System.out.println(7 / 2);
System.out.println(9 / 10);
System.out.println(7.0 / 2);
Output
3
0
3.5

As soon as one of the two numbers is a double, like 7.0, the division gives a double. With variables, turn an int into a double with a cast: (double) in front of it.

int sum = 7;
int count = 2;
double average = (double) sum / count;
System.out.println(average);
Output
3.5

Where the cast goes matters. (double) sum / count turns sum into 7.0 first and then divides, giving 3.5. (double) (sum / count) divides the two int values first, giving 3, and then turns that into 3.0.

Your task

Challenge 1 of 3

Put a cast in the blank, so the program prints the exact average, 2.5.

Challenge 2

Read two whole numbers and print their average as a decimal number. For the input 3 and 4 the program prints:

The average is 3.5

Challenge 3

Read three whole numbers and print their average. For the input 1, 2 and 3 the program prints:

The average is 2.0

A hidden test gives an average that doesn't come out even: it's printed with all the digits a double has.