Division Round Up in C++

Viewed 512

How can I round up when performing division on two int values in C++ without using std::ceil?

Typically I end up doing something like the following:

double res = ceil(a / (double) b);

Is there any way I can duplicate the result without using std::ceil?

2 Answers

If a and b are both positive, you can avoid floating point completely and get both exact results (no problems with FP rounding) and faster execution time through the classical method:

int res = (a + (b - 1)) / b;

For negative a you don't need any correction - the truncation performed by integer division already has the semantics matching your ceil formula; so, if you want a more general case:

int res = (a<0 ? a : (a + (b - 1))) / b;

you could do this

double res = (double) (((a % b) == 0) ? (a / b) : (a / b) + 1);

basically if there is a remainder, add 1 to the truncated integer result

Related