【问题标题】:Ruby modulo 3 with negative numbers is unintuitive带有负数的 Ruby 模 3 不直观
【发布时间】:2013-04-11 00:51:01
【问题描述】:

带有负数的 Ruby 模规则不清楚。在 IRB 中:

-7 % 3 == 2  

应该是1! 为什么?

【问题讨论】:

  • 不。应该是 2 或 -1,但从不 1。

标签: ruby modulo


【解决方案1】:

因为 -7/3 在 Ruby 的整数除法语义下是 -3。 3*-3 为 -9,因此余数为 2。

根据the docs,x模y定义为:

x-y*(x/y).floor

【讨论】:

    【解决方案2】:

    % 的操作数之一为负时,没有明确的最佳答案 返回什么结果。每种编程语言都有自己的规则。 Modulo operation 的维基百科页面有一个巨大的表格,说明如何 每种编程语言都决定处理这个问题,但没有明确的 共识:

    $ # Modulus sign is:
    $
    $ curl 'http://en.wikipedia.org/w/index.php?title=Modulo_operation&action=edit&section=1' \
        | egrep -o 'Divisor|Dividend|Always positive|Closest to zero|Not defined|Implementation defined' \
        | sort | uniq -c | sort -nr
    
      67 Dividend
      42 Divisor
       7 Always positive
       4 Closest to zero
       2 Not defined
       2 Implementation defined
    

    有些选择左侧操作数的符号,有些选择右侧操作数的符号 操作数。其他人不指定。例如,The C Programming Language 说:

    % [is] 负操作数的结果符号取决于机器

    C 并没有对如何处理这个问题做出特定的选择,而是 返回正在使用的特定硬件或编译器选择的任何内容 去执行!这似乎在最近的版本中已经标准化 的 C 编程语言标准。

    如果您想在 Ruby 中获得特定版本,有两种不同的 您可以调用的方法,modulo aka %remainder, 对负数有不同的行为:

    $ irb
    irb(main):001:0> -7.modulo(3)
    => 2
    irb(main):002:0> -7.remainder(3)
    => -1
    

    在其他没有内置方法的语言中,您可以结束 向上使用% 两次以获得所需的符号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 2014-04-12
      • 1970-01-01
      相关资源
      最近更新 更多