问题
i am basically coming from java background and struggling to understand the modulo operation in Ruby.
(5 % 3)
(-5 % 3)
(5 % -3)
(-5 % -3)
The above operation in Java yields, 2 -2 2 -2
But in Ruby, the same expression yields 2 1 -1 -2 .
How logically ruby is good at this? How the module operation is implemented in Ruby ? If the same operation is defined as a web services, how both services can match the logic.
回答1:
In Java, the result of the modulo operation has the same sign as the dividend.
In Ruby, it has the same sign as the divisor. remainder()
in Ruby has the same sign as the dividend.
You might also want to refer to modulo operation.
回答2:
Because Ruby defines x.modulo(y)
to be x-y*(x/y).floor
. See ruby-doc.org
回答3:
The sign of the remainder changes from language to language. The "right" way to do it is up for debate...
Ruby implements both ways. The remainder
function has the same behavior as Java, while modulo
and the %
operator use the other algorithm.
Wikipedia has a list of programming languages and how they implement modulo.
来源:https://stackoverflow.com/questions/20100537/why-ruby-modulo-is-different-from-java-other-lang