Ceil function: how can we implement it ourselves?

前端 未结 9 2048
别那么骄傲
别那么骄傲 2020-12-30 02:06

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

9条回答
  •  失恋的感觉
    2020-12-30 02:18

    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.


    * Not decimal point, because we're in base-2, not base-10.

提交回复
热议问题