Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the return type of the "ceil()" function "double" instead of some integer type?

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?

like image 425
Dominique Avatar asked Jan 23 '17 12:01

Dominique


People also ask

Why does ceil return double?

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.

What is the return type of Ceil function?

The ceil() function returns the integer as a double value.

Does Math ceil return an integer?

ceil() The Math. ceil() function always rounds up and returns the smaller integer greater than or equal to a given number.

Why does ceil return a float?

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.


1 Answers

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.

like image 197
Klas Lindbäck Avatar answered Sep 30 '22 06:09

Klas Lindbäck