Reliable method for rounding up integer division
Integer division rounds towards zero by default, which can cause problems. To ensure that we always round up, we need a better solution.
In the example provided in the article, converting the operand to a double precision floating point number and using Math.Ceiling()
is a possible workaround, but this is considered non-standard and inefficient.
We recommend the following methods:
1. Clearly define specifications
2. Design testable algorithms
Break the problem into smaller steps:
3. Implement the solution
The following is an example implementation:
<code class="language-java">public static int DivRoundUp(int dividend, int divisor) { if (divisor == 0) throw new IllegalArgumentException("除数为零"); if (divisor == -1 && dividend == Integer.MIN_VALUE) throw new ArithmeticException("整数溢出"); int quotient = dividend / divisor; boolean dividedEvenly = (dividend % divisor) == 0; if (dividedEvenly) return quotient; boolean roundedDown = ((divisor > 0) == (dividend > 0)); return roundedDown ? quotient + 1 : quotient; }</code>
This algorithm conforms to the specified behavior of rounding up all non-divisible division results. It also handles overflow and divide-by-zero errors very well. While this isn't the most elegant solution, it's clear, testable, and correct.
The above is the detailed content of How Can We Ensure Integer Division Always Rounds Up?. For more information, please follow other related articles on the PHP Chinese website!