I am dividing 2 integers and looking to get an integer as a result. I want the right Math.Round()
method so when I divide, it always round to the next integer regardless of how. Here are a bunch of examples with expectations below.
int result = (6/4); // = 2
int result = (3/4); // = 1
int result = (1/4); // = 1
int result = (8/4); // = 2
int result = (9/4); // = 3
What is the correct way of doing this?
Since all the integers in your example are positive, I'll assume that you are not interested in the case where one or both operands are negative or zero.
Math.Round
works on floating-point numbers. That is not necessary here.
Dividing two integers gives an integer result. It always rounds down. You want something like this:
int Divide(int numerator, int denominator) {
return (numerator + denominator - 1) / denominator;
}
For example,for 1/4
, we get (1 + 4 - 1) / 4 = 4 / 4 = 1
, and for 8/4
we get (8 + 4 - 1) / 4 = 11 / 4 = 2
.
There's a very slight possibility of overflow here, so if the numerator is always greater than zero, it's better to use:
int Divide(int numerator, int denominator) {
return 1 + (numerator - 1) / denominator;
}
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