Ceil function: how can we implement it ourselves?

前端 未结 9 1990
别那么骄傲
别那么骄傲 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:35

    Here is a naive implementation for positive numbers (this uses the fact that casting to (int) truncates toward zero):

    int ceil(float num) {
        int inum = (int)num;
        if (num == (float)inum) {
            return inum;
        }
        return inum + 1;
    }
    

    It is easy to extend this to work with negative numbers too.

    Your question asked for a function returning int, but normally the ceil() function returns the same type as its argument so there are no problems with the range (that is, float ceil(float num)). For example, the above function will fail if num is 1e20.

    0 讨论(0)
  • 2020-12-30 02:35

    Something like this:

      double param, fractpart, intpart;
    
      param = 3.14159265;
      fractpart = modf (param , &intpart);
    
      int intv = static_cast<int>(intpart); // can overflow - so handle that.
    
      if (fractpart > some_epsilon)
        ++intv;
    

    You just need to define some_epsilon value to whatever you want the fractional part to be bigger than before the integer part is incremented. Other things to consider are sign (i.e. if the value is negative etc.)

    0 讨论(0)
  • 2020-12-30 02:36

    Try this...

    int ceil(float val)
    {
        int temp  = val * 10;
        if(val%10)
        return (temp+1);
        else
        return temp;
    }
    
    0 讨论(0)
提交回复
热议问题