Why do integer div and mod round towards zero?
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 i开发者_StackOverflowndex using modulo array.length
.
This is no rant, I'm really interested if there are uses for this definition.
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.
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
.)
精彩评论