I've just implemented a line of code, where two numbers need to be divided and the result needs to be rounded up to the next integer number. I started very naïvely:
i_quotient = ceil(a/b);
As the numbers a
and b
are both integer numbers, this did not work: the division gets executed as an integer division, which is rounding down by default, so I need to force the division to be a floating point operation:
i_quotient = ceil((double) a / b);
Now this seems to work, but it leaves a warning saying that I am trying to assign a double to an integer, and indeed, following the header file "math.h" the return type of the ceil()
function is "double", and now I'm lost: what's the sense of a rounding function to return a double? Can anybody enlighten me about this?
Math. ceil() returns the double value that is greater than or equal to the argument and is equal to the nearest mathematical integer. Note: If the argument is Integer, then the result is Integer.
The ceil() function returns the integer as a double value.
ceil() The Math. ceil() function always rounds up and returns the smaller integer greater than or equal to a given number.
There are floating point numbers that do not fit into an integer, so the function would fail if it returned an integer. Returning the same type as the parameter ensures the result will fit.
A double has a range that can be greater than any integer type.
Returning double
is the only way to ensure that the result type has a range that can handle all possible input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With