问题
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)
, thenq = 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