It works if you round the result down afterwards.
Let’s take e.g. a=3 and b=5. Without rounding a/b = 0.6. Rounded down it’s 0. Rounded up it’s 1. More generally, the result rounded up will always be 1 larger, unless the result is already an integer: Rounding 5/5 = 1 up and down both result in 1.
To get from a rounded down result to a rounded up result you could always add 1, but that produces the wrong result if a was a multiple of b. To fix that, we subtract 1 from a beforehand. If and only if a is a multiple of b this will make us round down, reducing the result by 1. So (a-1)/b + 1, rounded down, is equal to a/b rounded up. We can rewrite (a-1)/b + 1 = (a+b-1)/b as b/b=1 and that doesn’t change the rounding either.
Why do all these things? Computers generally round down. This is a way to get “round up” without adding extra hardware or more complicated logic to do so.
Latest Answers