Skip to main content

Section 3.9 Integer Division

The program below divides 45 by 60. Before you run it, stop and think about what you expect the output to be:
Listing 3.9.1.
This behavior often confuses people. The value of minute is 45, and 45 divided by 60 should be 0.75, not 0. So why is 0 produced?
The reason this program behaves the way it does is that C++ performs integer division when both operands are integers. Integer division always results in a whole number (integer) answer. The division produces an integer answer by truncating the result of the division. Truncating a value means dropping the decimal portion. Here, 45 / 60 produces 0.75 and that is truncated to 0. Note that truncation does not mean rounding the value - 0.75 becomes 0, not 1.

Insight 3.9.1.

When dividing integers, C++ does whole number division. 7 / 3 asks “how many whole times does 3 divide into 7?”. The answer is 2.
As an alternative, we can calculate a percentage rather than a fraction:
Listing 3.9.2.
Because the multiplication happens first, we get 4500 / 60, which is 75. (The multiplication would happen first here no matter what, but the parentheses help make the intended order of operations clear.)

Note 3.9.2.

Also note that the print statement is broken up over multiple lines. Remember that C++ does not care about extra whitespace (things like spaces and newlines). Breaking up a long statement of code over multiple lines can help make it easier to read. Just make sure to break up code at logical places - like before operators - and to use indentation to make it clear that the extra lines are a continuation of a statements.
The order of operations is critical here. If we change the logic to do the division first, as shown below, we are back to 0 for our result. The first thing evaluated is minute / 60, which is 0. Multiplying that by 100 results in 0.
Listing 3.9.3.

Checkpoint 3.9.1.

Checkpoint 3.9.2.

Checkpoint 3.9.3.

Checkpoint 3.9.4.

Checkpoint 3.9.5.

Checkpoint 3.9.6.

You have attempted of activities on this page.