views:

428

answers:

3

Once in a while, I find myself rounding 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 number, and not an integer ? I find this pretty non-intuitive, and would love to have some explanations !

+17  A: 

That's because float's range is wider than int's. What would you expect to have if the value returned by these functions did not fit into an int? That would be undefined behaviour and you would be unable to check for that in your program.

sharptooth
Thanks for your answer !
Wookai
There would not need to be any undefined behaviour - the functions *could* have been specified to return an error value in that case, just like strtol() does if the number to be converted doesn't fit into a long. The reason is simply that the functions would be far less useful if they were restricted to the range of int.
caf
+21  A: 

The integral value returned by these functions may be too large to store in an integer type (int, long, etc.). To avoid an overflow, which will produce undefined results, an application should perform a range check on the returned value before assigning it to an integer type.

from the ceil(3) Linux man page.

Sean A.O. Harney
Thanks for the answer, I accepted your because you were first ;) !
Wookai