round() for float in C++

后端 未结 22 1203
时光取名叫无心
时光取名叫无心 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

    Based on Kalaxy's response, the following is a templated solution that rounds any floating point number to the nearest integer type based on natural rounding. It also throws an error in debug mode if the value is out of range of the integer type, thereby serving roughly as a viable library function.

        // round a floating point number to the nearest integer
        template 
        int Round(Arg arg)
        {
    #ifndef NDEBUG
            // check that the argument can be rounded given the return type:
            if (
                (Arg)std::numeric_limits::max() < arg + (Arg) 0.5) ||
                (Arg)std::numeric_limits::lowest() > arg - (Arg) 0.5)
                )
            {
                throw std::overflow_error("out of bounds");
            }
    #endif
    
            return (arg > (Arg) 0.0) ? (int)(r + (Arg) 0.5) : (int)(r - (Arg) 0.5);
        }
    

提交回复
热议问题