对负数取模 [英] modulo operation on negative numbers
问题描述
模运算a%b
返回a/b
的余数,但对于负数则不这样做.
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;
}
它应该返回2,因为3 *(-2)=-6小于-4且是3的倍数,但输出为-1.
为什么将(-a) mod b
与-(a mod b)
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)
推荐答案
作为一般规则,模和除法应满足方程式
As a general rule, the modulo and division should satisfy the equation
b * (a/b) + a%b == a
对于正数,很明显,这意味着a%b
必须为正数.但是,如果a/b
为负,则结果将四舍五入为零.
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.
因此,以 a = -4, b = 3为例.我们知道 a / b = -1.3333,四舍五入为a/b == -1
.从上面的方程式中,我们可以得到b * (-1) + a%b == a
.如果我们插入a
和b
,则会得到-3 + a%b == -4
,并且看到a%b
必须为-1.
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.
这篇关于对负数取模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!