我有几行C代码测试模运算符如下:
// line 1
printf("%d\n", 5 % (-3)); => output: 2
// line 2
printf("%d\n", -5 % 3); => output: -2
我知道模数的符号取决于分子的符号,但我很好奇为什么不这样做呢?
答案 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