While programming I often find myself needing to calculate something like:
x = (y / n) + (y % n ? 1 : 0);
Or more explicitly:
x = y / n;
if (y % n != 0) {
x = x + 1;
}
Is there a more elegant way to achieve this value? Can it be achieved without using a conditional expression?
So, you want the integer division to round up instead of down. You can fake this by adding n-1
to the numerator:
x = (y + n - 1) / n;
That way you shift the value it'll be rounded down to just enough to give you the desired outcome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With