取模运算结果的符号是什么?

5

我有几行C代码用于测试模运算符,如下所示:

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

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


请参见http://stackoverflow.com/a/6385400/253056。 - Paul R
2
这不是一个应该被投反对票的问题。这是关于模运算符如何工作的问题,也是一个好问题。 - Richard J. Ross III
我非常确定,任何%和负数的组合的结果都是由具体实现定义的。 - cHao
1
在 C99 之前,它是实现定义的 - 请参阅先前的重复问题。 - Paul R
1个回答

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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接