What's the difference between “mod” and “remainder”?

后端 未结 5 837

My friend said that there are differences between \"mod\" and \"remainder\".

If so, what are those differences in C and C++? Does \'%\' mean either \"mod\" or \"rem\

5条回答
  •  鱼传尺愫
    2020-11-22 04:35

    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);

    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.

提交回复
热议问题