Need help understading expression.

Hi everyone,

I'm new to both C++ and these forums. I'm reading up on the language but can't seem to get this expression wrapped around my head.

expression:

((total % 3) == 2)

From what I can figure, if my variable (total) divided by 3 is equal to 2 then the expression is true correct?

But for example I enter 11 as the variable, which is not divisible by 3, statement still comes out true.

Thanks,
closed account (zb0S216C)
rutski76 wrote:
From what I can figure, if my variable (total) divided by 3 is equal to 2 then the expression is true correct?

In C/C++, the percentage is modulus. With the modulus operator, the remainder of a division is its return value. That said, if the remainder of the division is equal to 2, then the expression is true. Otherwise, it's false.

Wazzak
Sorry,

I'm still not fully understanding. Using the above example; 11 / 3 = 3.6~ how is that equal to 2?
closed account (zb0S216C)
The modulus operator returns the remainder of a division, not the amount of times the left-hand operand went into the right-hand operand (an operand is a piece of data on either side of an operator). For instance, 11 / 3 is two. Here's why:

11 - 3 = 8
8 - 3 = 5
5 - 3 = 2
2 - 3 = ??

The last calculation can't be done because 3 is greater. Because we can no longer divide 2 by 3, 2 becomes the remainder.

Wazzak
Last edited on
The % is the modulus operator that gives the remainder of a division.

11 divided by 3 gives 3 remainder 2. (i.e. (3 x 3)+2 = 11)

% returns the 2.
Nice!

I totally get it now!!!

Thanks!
Topic archived. No new replies allowed.