【问题标题】:The sign of the modulo operator result? [duplicate]模运算符结果的符号? [复制]
【发布时间】:2012-02-28 00:35:28
【问题描述】:

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

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

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

【问题讨论】:

  • 这不是一个可以投反对票的问题。这是一个模运算符如何工作的问题,是一个很好的问题。
  • 我很确定% 和负数的几乎任何组合的结果都是实现定义的。
  • 它是 C99 之前的实现定义 - 请参阅以前的副本

标签: c modulo


【解决方案1】:
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 

【讨论】:

    猜你喜欢
    • 2012-10-24
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多