modulo operation on negative numbers [duplicate]

独自空忆成欢 提交于 2019-12-02 07:49:07

As a general rule, the modulo and division should satisfy the equation

b * (a/b) + a%b == a

For positive numbers, it is obvious that this means that a%b must be a positive number. But if a/b is negative, then the result is rounded towards zero.

So take for instance a = -4, b = 3. We know that a/b = -1.3333, which rounded towards zero becomes a/b == -1. From the equation above, we have that b * (-1) + a%b == a. If we insert a and b, we get -3 + a%b == -4, and we see that a%b must be -1.

Your suffering stems from embracing the illusion that % is a "modulo" operator. In truth, it is a remainder operator (C11 §6.5.5):

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder

Reject the illusion and accept the truth, and the behavior of the operator will become clear (Ibid.):

If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a

In your case, a/b is -4/3, which is -1, hence representable. So a%b satisfies:

(a/b)*b + a%b =  a
(-1)*3  + a%b = -4
  -3    + a%b = -4
          a%b = -1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!