round() for float in C++

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

    There is no need to implement anything, so I'm not sure why so many answers involve defines, functions, or methods.

    In C99

    We have the following and and header for type-generic macros.

    #include 
    double round (double x);
    float roundf (float x);
    long double roundl (long double x);
    

    If you cannot compile this, you have probably left out the math library. A command similar to this works on every C compiler I have (several).

    gcc -lm -std=c99 ...
    

    In C++11

    We have the following and additional overloads in #include that rely on IEEE double precision floating point.

    #include 
    double round (double x);
    float round (float x);
    long double round (long double x);
    double round (T x);
    

    There are equivalents in the std namespace too.

    If you cannot compile this, you may be using C compilation instead of C++. The following basic command produces neither errors nor warnings with g++ 6.3.1, x86_64-w64-mingw32-g++ 6.3.0, clang-x86_64++ 3.8.0, and Visual C++ 2015 Community.

    g++ -std=c++11 -Wall
    

    With Ordinal Division

    When dividing two ordinal numbers, where T is short, int, long, or another ordinal, the rounding expression is this.

    T roundedQuotient = (2 * integerNumerator + 1)
        / (2 * integerDenominator);
    

    Accuracy

    There is no doubt that odd looking inaccuracies appear in floating point operations, but this is only when the numbers appear, and has little to do with rounding.

    The source is not just the number of significant digits in the mantissa of the IEEE representation of a floating point number, it is related to our decimal thinking as humans.

    Ten is the product of five and two, and 5 and 2 are relatively prime. Therefore the IEEE floating point standards cannot possibly be represented perfectly as decimal numbers for all binary digital representations.

    This is not an issue with the rounding algorithms. It is mathematical reality that should be considered during the selection of types and the design of computations, data entry, and display of numbers. If an application displays the digits that show these decimal-binary conversion issues, then the application is visually expressing accuracy that does not exist in digital reality and should be changed.

提交回复
热议问题