This question already has answers here:
Modulo operation with negative numbers

(12个答案)



Problem using modulo with negative numbers in decryption program

(2个答案)


2年前关闭。




我有几行测试模运算符的C代码,如下所示:
// line 1
printf("%d\n", 5 % (-3)); => output: 2
// line 2
printf("%d\n", -5 % 3); => output: -2

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

最佳答案

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

09-26 22:51