Card 03/ 09
All 9 cards
ExampleDifficulty: Beginner1 min
Dividing Two Whole Numbers and Losing the Remainder
A progress figure that reports zero per cent for the first ninety-nine items of a hundred, and then jumps to one hundred.
int done = 40;
int total = 100;
double percent = done / total * 100;
System.out.println(percent);0.0done / total is two int values, so / is whole-number division. Forty divided by a hundred is zero with a remainder of forty, and the remainder is thrown away before * 100 ever happens. Declaring the result as double changed nothing, because the damage was done inside the expression.
Multiplying first fixes it, and so does making one operand a double: done * 100.0 / total gives 40.0.
This and the string case are the same fact wearing different clothes. In both, an operator did a different job than the one you read, because the types either side of it chose the job — and in both the compiler was happy, because both jobs were legal.