round() for float in C++

后端 未结 22 1217
时光取名叫无心
时光取名叫无心 2020-11-22 03:01

I need a simple floating point rounding function, thus:

double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

I can find

22条回答
  •  灰色年华
    2020-11-22 03:30

    Function double round(double) with the use of the modf function:

    double round(double x)
    {
        using namespace std;
    
        if ((numeric_limits::max() - 0.5) <= x)
            return numeric_limits::max();
    
        if ((-1*std::numeric_limits::max() + 0.5) > x)
            return (-1*std::numeric_limits::max());
    
        double intpart;
        double fractpart = modf(x, &intpart);
    
        if (fractpart >= 0.5)
            return (intpart + 1);
        else if (fractpart >= -0.5)
            return intpart;
        else
            return (intpart - 1);
        }
    

    To be compile clean, includes "math.h" and "limits" are necessary. The function works according to a following rounding schema:

    • round of 5.0 is 5.0
    • round of 3.8 is 4.0
    • round of 2.3 is 2.0
    • round of 1.5 is 2.0
    • round of 0.501 is 1.0
    • round of 0.5 is 1.0
    • round of 0.499 is 0.0
    • round of 0.01 is 0.0
    • round of 0.0 is 0.0
    • round of -0.01 is -0.0
    • round of -0.499 is -0.0
    • round of -0.5 is -0.0
    • round of -0.501 is -1.0
    • round of -1.5 is -1.0
    • round of -2.3 is -2.0
    • round of -3.8 is -4.0
    • round of -5.0 is -5.0

提交回复
热议问题