Task 7 of 14 · 0 solved · 14 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

1.4 Arithmetic — mixed types and casting

Lesson

Mixing int and double

If either operand is a double, the whole operation is done in double and the result has a fractional part: 9 / 2.0 is 4.5. A cast (double) changes a value's type on the spot.


Watch where the cast applies

System.out.println(9 / 2);           // 4    (both int)
System.out.println(9 / 2.0);         // 4.5  (one double)
System.out.println((double)9 / 2);   // 4.5  (9 becomes 9.0 first)
System.out.println((double)(9 / 2)); // 4.0  (int 9/2=4 first, then cast)

The last one is the trap: the division happens before the cast, so the fractional part is already lost.


▶ Try it: run this, then change something and run it again.



What does System.out.println(9 / 2.0); print?


What does System.out.println(7 / 2.0); print?


What does System.out.println((double)(9 / 2)); print?


Type exactly what this prints:

System.out.println(9.0 / 2);

Fill the blank so the division gives 4.5 (a decimal), not 4.


Task

Write the body of half that takes an int n and returns half of it as a decimal (a double).

For example, half(7) returns 3.5; half(4) returns 2.0.