Why modulus operation work different in ruby than other languages?

て烟熏妆下的殇ゞ 提交于 2021-01-29 02:30:49

问题


In Ruby, I get:

-5 % 3 # => 1

whereas other languages like PHP, Javascript, C++, and Java all produce the result -2. I don't understand this concept. I hope someone can explain this ruby's calculation method. It would be better if you could use an example of how it works.


回答1:


It's in the docs: https://ruby-doc.org/core-2.5.0/Numeric.html#method-i-divmod

If q, r = x.divmod(y), then

q = floor(x/y)
x = q*y + r

The quotient is rounded toward negative infinity

So q is -3 (-5 / 2 and round down, as per usual integer division rules). And r = x - q * y = -5 - -3 * 2 = 1



来源:https://stackoverflow.com/questions/53378554/why-modulus-operation-work-different-in-ruby-than-other-languages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!