Why ruby modulo is different from java/other lang ?

前端 未结 3 1303
天涯浪人
天涯浪人 2021-01-18 09:42

i am basically coming from java background and struggling to understand the modulo operation in Ruby.

(5 % 3)     
(-5 % 3)    
(5 % -3)    
(-5 % -3) 


        
相关标签:
3条回答
  • 2021-01-18 10:28

    Because Ruby defines x.modulo(y) to be x-y*(x/y).floor. See ruby-doc.org

    0 讨论(0)
  • 2021-01-18 10:34

    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.

    0 讨论(0)
  • 2021-01-18 10:39

    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.

    0 讨论(0)
提交回复
热议问题