Why do integer div and mod round towards zero?

时光总嘲笑我的痴心妄想 提交于 2019-12-12 11:01:01

问题


Unlike in C, in Java is the result of x/y and x%y well-defined even for negative operands. Surprisingly, it's defined by rounding towards zero, and not by rounding down (i.e., towards negative infinity). Does anybody have taken any advantage of this definition?

In most cases I just don't care, but sometimes I had to work around this, e.g., when computing an index using modulo array.length.

This is no rant, I'm really interested if there are uses for this definition.


回答1:


It's easier to implement a division routine if you can round toward zero. Often, a division involving a negative is sign-flipped, and then the division carried out on a positive equivalent, and then the answer flipped back again. So the effect is naturally going to be round toward zero.




回答2:


Here's one example where it's useful, however slightly:

maxPage = (rows.length - 1) / ROWS_PER_PAGE

(No need to special case for maxPage = 0 when rows.length = 0, assuming ROWS_PER_PAGE > 1.)



来源:https://stackoverflow.com/questions/5682625/why-do-integer-div-and-mod-round-towards-zero

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