Why don't round () and ceil () return an integer?

From time to time, I find that I am rounding off some numbers, and I always have to cast the result to an integer:

int rounded = (int) floor(value); 

Why do all rounding functions ( ceil() , floor() ) return a floating-point number rather than an integer? I find this rather unintuitive and would like some explanation!

+52
c ++ c casting rounding
Aug 10 '09 at 8:16
source share
2 answers

The integral value returned by these functions may be too large to be stored in an integer type (int, long, etc.). To avoid overflow, which will lead to undefined results, the application must check the range of the return value before assigning an integer type.

on the ceil (3) Linux man page.

+62
Aug 10 '09 at 8:20
source share

This is because the range of float wider than int . What would you expect if the value returned by these functions was not in the int ? This will be undefined behavior, and you will not be able to verify this in your program.

+26
Aug 10 '09 at 8:19
source share



All Articles