Why ruby modulo is different from java/other lang ?

若如初见. 提交于 2020-11-29 04:41:41

问题


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

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