round() for float in C++

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

    If you need to be able to compile code in environments that support the C++11 standard, but also need to be able to compile that same code in environments that don't support it, you could use a function macro to choose between std::round() and a custom function for each system. Just pass -DCPP11 or /DCPP11 to the C++11-compliant compiler (or use its built-in version macros), and make a header like this:

    // File: rounding.h
    #include 
    
    #ifdef CPP11
        #define ROUND(x) std::round(x)
    #else    /* CPP11 */
        inline double myRound(double x) {
            return (x >= 0.0 ? std::floor(x + 0.5) : std::ceil(x - 0.5));
        }
    
        #define ROUND(x) myRound(x)
    #endif   /* CPP11 */
    

    For a quick example, see http://ideone.com/zal709 .

    This approximates std::round() in environments that aren't C++11-compliant, including preservation of the sign bit for -0.0. It may cause a slight performance hit, however, and will likely have issues with rounding certain known "problem" floating-point values such as 0.49999999999999994 or similar values.

    Alternatively, if you have access to a C++11-compliant compiler, you could just grab std::round() from its header, and use it to make your own header that defines the function if it's not already defined. Note that this may not be an optimal solution, however, especially if you need to compile for multiple platforms.

提交回复
热议问题