Dave Dave - 1 month ago 8
C Question

C - Rounding integer division (instead of truncating)

I was curious to know how I can round a number to the nearest tenth whole number. For instance, if I had:

int a = 59 / 4;

which would be 14.75 calculated in floating point; how can I store the number as 15 in "a"?

int a = 59.0f / 4.0f + 0.5f;

This only works when assigning to an int as it discards anything after the '.'

Edit: This solution will only work in the simplest of cases. A more robust solution would be:

unsigned int round_div(unsigned int dividend, unsigned int divisor)
    return (dividend + (divisor / 2)) / divisor;