Is there any effective way to round a division?

Round to next integer that is. If the remainders are 0,5<, then it should be rounded down to next integer and when it's 0,5>=, then it should be rounded up to next integer. Say, I have 8593/3384, which is about 2,53. It should be rounded to 3. Then if I have 9/4, which is 2,25, it should be rounded to 2.

I tried to do it somehow like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
int example(){
int a = 9;
int b = 4;
inc c = 9/4;
int d = 9%4;
double e = d/b;
if (e < 0,5){
return c++;
}
else{
return c;
}
}

But that's such a clumsy way and in many cases, doubles of floats are very inaccurate. Is there any effective way to do this?
Conversion to integer drops the remainder. Floating point numbers are inaccurate. Therefore, the following is inaccurate too:
1
2
3
int a = 9;
int b = 4;
int c = static_cast<double>( a ) / b + 0.5;

Question is, how often does it fail in practice?
It doesn't need to be 100% accurate, but there doesn't seem to be a way to have it 100%. I guess that will do, thanks.
Thinking a bit further, since we have integers:
1
2
3
4
int c = a / b;
int d = a % b;
int e = b - d;
c += ( d < e ) ? 0 : 1;

That should be accurate for all positive inputs, and does not have if-else branching. Efficiency ... you could test

integer division
integer modulo
integer substraction
conditional expression with integer comparison

vs.

conversion to double
double division
double addition
conversion to int
Topic archived. No new replies allowed.