带有负数的Ruby模3是不直观的 [英] Ruby modulo 3 with negative numbers is unintuitive

查看:72
本文介绍了带有负数的Ruby模3是不直观的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ruby modulo rules with negative numbers are unclear. In IRB:

-7 % 3 == 2  

应该是1! 为什么?

推荐答案

%的操作数之一为负数时,没有明确的最佳答案 返回什么结果.每种编程语言都有其自己的规则. Wikipedia页面上的 Modulo操作有一个庞大的表格 每种编程语言都已决定要解决此问题,目前尚无明确的方法 共识:

When one of the operands to % is negative, there’s no clear best answer for what result to return. Every programming language has its own rules. The Wikipedia page for Modulo operation has a giant table of how each programming language has decided to handle this, and there’s no clear consensus:

$ # 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

有些选择左操作数的符号,有些选择右操作数 操作数.其他人未指定.例如, C编程语言 说:

Some choose the sign of the left-hand operand, and some the right-hand operand. Others don’t specify. For example, The C Programming Language says:

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

the sign of the result for % [is] machine-dependent for negative operands

C并没有为如何处理这一问题做出特定选择,而只是 返回所使用的特定硬件或编译器选择的内容 实施!这似乎已经在较新的版本中进行了标准化 C编程语言标准.

Instead of making a particular choice for how to handle this, C just returns whatever the particular hardware or compiler being used have chosen to implement! This seems to have been standardized in more recent versions of the C programming language standards.

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

If you want to get a particular version in Ruby, there are two different methods you could call, modulo aka %, and remainder, with different behaviour on negative numbers:

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

在其他没有内置方法的语言中,您可能会结束 两次使用%来获得所需的符号.

In other languages that don’t have built-in methods for this, you may end up using % twice to get the desired sign.

这篇关于带有负数的Ruby模3是不直观的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆