模运算符结果的符号?

时间:2012-02-06 14:36:00

标签: c modulo

我有几行C代码测试模运算符如下:

// line 1
printf("%d\n", 5 % (-3)); => output: 2
// line 2
printf("%d\n", -5 % 3); => output: -2

我知道模数的符号取决于分子的符号,但我很好奇为什么不这样做呢?

1 个答案:

答案 0 :(得分:3)

5/(-3) = -1;
(-5)/3 = -1; 

If that is agreed then let's calculate the remainder

Remainder = Dividend - ( Divisor * Factor)

5 - (-3 * -1) = 2
-5 - (3 * -1) = -2