Ceil function: how can we implement it ourselves?

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

    You can take apart the ingredients of an IEEE754 floating point number and implement the logic yourself:

    #include 
    
    float my_ceil(float f)
    {
        unsigned input;
        memcpy(&input, &f, 4);
        int exponent = ((input >> 23) & 255) - 127;
        if (exponent < 0) return (f > 0);
        // small numbers get rounded to 0 or 1, depending on their sign
    
        int fractional_bits = 23 - exponent;
        if (fractional_bits <= 0) return f;
        // numbers without fractional bits are mapped to themselves
    
        unsigned integral_mask = 0xffffffff << fractional_bits;
        unsigned output = input & integral_mask;
        // round the number down by masking out the fractional bits
    
        memcpy(&f, &output, 4);
        if (f > 0 && output != input) ++f;
        // positive numbers need to be rounded up, not down
    
        return f;
    }
    

    (Insert the usual "not portable" disclaimer here.)

提交回复
热议问题