Burre Ifort
Burre Ifort

Reputation: 713

Confused with % operator

I have this simple line of code which shows as remainder 5:

Console.WriteLine(5 % 8);

The % operator shows the remainder after first number and second number are divided. So, 5 / 8 = 0,625. Shouldn't the reminder of the code above be 6 instead of 5? Why do I see 5 when I test in Visual Studio?

Upvotes: 0

Views: 291

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 659956

Everything follows from the fundamental rules of integer division. For integers x and y suppose we have:

q = x / y;
r = x % y;

The fundamental rules are:

  • q and r are both integers
  • q * y + r == x
  • Division rounds towards zero when inexact

Now that you know the fundamental rules you can work out the values of 5 / 8 and 5 % 8.

5 / 8 is an integer. The exact value is 0.625, but that's not an integer, so we round towards zero and get 0. So q is 0.

To compute r we must solve for q * 8 + r = 5, which is easy to solve: r = 5 is the solution.

(Note that there are a few more fundamental rules about dividing by zero, and so on, that you usually don't have to worry about.)

Upvotes: 2

gunr2171
gunr2171

Reputation: 17447

How many times does 8 go "cleanly" into 5? Zero times.

5 / 8 = 0 (int division)

When you do 5 ÷ 8, how many items are left over? 5.

5 % 8 = 5 (modulus division)

Another way to explain this is:

You have 5 apples. Please distribute those apples among 8 groups, but you must ensure that every group has an equal amount of apples.

You can't do that. You have less apples than the number of groups. You can't give any apples to anyone.

And because you didn't give any apples away, you are left with 5 apples. That is your remainder.

Upvotes: 2

dzl
dzl

Reputation: 906

Modulo doesn't give you the first number of the quotient, but the remainder after the second number is divided by the first.

8 doesn't go into 5 at all, so the remainder is the full 5.

See this answer for several other good explanations:

How does a modulo operation work when the first number is smaller?

Upvotes: 0

Related Questions