Card 03/ 09

ExampleDifficulty: Beginner1 min

Integer Division Example: A Percentage That Reports Zero

Zero per cent for the first ninety-nine items of a hundred, then a jump to one hundred.

Dividing one int by another gives a whole number: the remainder is thrown away, not rounded. A progress figure that divides items done by items in total shows it, reporting zero per cent until the very last item:

java
int done = 40;
int total = 100;

double percent = done / total * 100;
System.out.println(percent);
text
0.0

done / 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, one of the values the operator works on, a double: done * 100.0 / total gives 40.0.

This and "5" + 3 giving "53" are the same fact in 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.