modulo operation on negative numbers [duplicate]

纵饮孤独 提交于 2019-12-02 16:14:43

问题


A modulo operation a%b returns the remainder for a/b but for negative numbers it does not do so.

#include <stdio.h>

int main(void) {
  int n=-4;
  printf("%d\n",n%3);
  return 0;
}

It should return 2 as 3*(-2)=-6 is just smaller than -4 and a multiple of 3 but the output is -1. Why is it treating (-a) mod b same as -(a mod b)


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/30199474/modulo-operation-on-negative-numbers

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