I know that C++ provides us with a ceil function. For practice, I was wondering how can we implement the ceil function in C++. The signature of the method is public static
That is essentially what you have to do, but without converting to string
.
A floating-point number is represented as (+/-) M * 2^E
. The exponent, E
, tells you how far away you are from the binary point*. If E
is big enough, there is no fractional part, so there's nothing to do. If E
is small enough, there is no integer part, so the answer is 1 (assuming M
is non-zero, and the number is positive). Otherwise, E
tells you where the binary point appears within your mantissa, which you can use to do a check, and then perform rounding.