In C and C++ and many languages, %
is the remainder NOT the modulus operator.
For example in the operation -21 / 4
the integer part is -5
and the decimal part is -.25
. The remainder is the fractional part times the divisor, so our remainder is -1
. JavaScript uses the remainder operator and confirms this
console.log(-21 % 4 == -1);
_x000D_
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.