Integer Division

Division in C++ has a catch. Try to guess what this statement prints:

std::cout << 7 / 2 << "\n";

This prints:

3

Not 3.5, but 3. When you divide two whole numbers, the result is a whole number too: C++ throws away the decimal part. It doesn't round, it just cuts it off, so 19 / 10 is 1, and 2 / 3 is 0. This is called integer division.

Integer division works like division with a remainder from primary school: how many times one number fits into another. The remainder is given by the % operator (the percent sign, which programmers call modulo):

std::cout << 7 / 2 << "\n";
std::cout << 7 % 2 << "\n";
std::cout << 10 % 5 << "\n";

This prints:

3
1
0

Two fits into seven three times (3 × 2 = 6), and 1 is left over. When the division works out exactly, the remainder is 0. That's how you recognize even numbers: an even number divided by two leaves a remainder of 0, an odd number leaves 1. The % operator works only with whole numbers.

If you want a decimal result, at least one of the numbers has to be a decimal number:

std::cout << 7.0 / 2 << "\n";
std::cout << 7 / 2.0 << "\n";
std::cout << 10.0 / 3 << "\n";

This prints:

3.5
3.5
3.33333

std::cout prints decimal numbers with at most 6 significant digits, which is why you see 3.33333.

A typical mistake is to think that storing the result in a double is enough:

double half = 7 / 2;
std::cout << half << "\n";

This prints:

3

C++ calculates 7 / 2 first. Both numbers are whole, so the result is 3, and only then is that 3 stored in half. The type of the variable on the left of = doesn't matter.

And what if you divide two variables of type int? Convert one of them to a decimal number with static_cast<double>(...):

int points = 7;
int games = 2;
std::cout << static_cast<double>(points) / games << "\n";

This prints:

3.5

static_cast<double>(points) takes the value of points as a decimal number. The variable itself stays an int.

Instructions

Four friends ordered pizzas, cut into 18 slices altogether. How many whole slices does each of them get? Calculate it from the variables and print:

Slices each: 4

How many slices are left over? Calculate it with % and print it on the next line:

Slices left: 2

The bill is 50 EUR, and the friends split it equally. On the next line, print how much each of them pays. With integer division, it would come out as only 12, and 2 EUR would be missing:

Each pays: 12.5 EUR

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/9