c/c++ notation of double floating point values

前端 未结 2 1713
醉酒成梦
醉酒成梦 2020-12-21 19:38

What\'s the notation for double precision floating point values in C/C++?

.5 is representing a double or a float value?

I\'m pretty sure 2.0

相关标签:
2条回答
  • 2020-12-21 20:27

    Technically, initializing a float with a double constant can lead to a different result (i.e. cumulate 2 round off errors) than initializing with a float constant.

    Here is an example:

    #include <stdio.h>
    int main() {
        double d=8388609.499999999068677425384521484375;
        float f1=8388609.499999999068677425384521484375f;
        float f2=8388609.499999999068677425384521484375;
        float f3=(float) d;
        printf("f1=%f f2=%f f3=%f\n",f1,f2,f3);
    }
    

    with gcc 4.2.1 i686 I get

    f1=8388609.000000 f2=8388610.000000 f3=8388610.000000
    

    The constant is exactly in base 2:

    100000000000000000000001.011111111111111111111111111111
    

    Base 2 representation requires 54 bits, double only have 53. So when converted to double, it is rounded to nearest double, tie to even, thus to:

    100000000000000000000001.10000000000000000000000000000
    

    Base 2 representation requires 25 bits, float only have 24, so if you convert this double to a float, then another rounding occur to nearest float, tie to even, thus to:

    100000000000000000000010.
    

    If you convert the first number directly to a float, the single rounding is different:

    100000000000000000000001.
    

    As we can see, when initializing f2, gcc convert the decimal representation to a double, then to a float (it would be interesting to check if the behaviour is determined by a standard).

    Though, as this is a specially crafted number, most of the time you shouldn't encounter such difference.

    0 讨论(0)
  • 2020-12-21 20:30

    It's double. Suffix it with f to get float.

    And here is the link to reference document: http://en.cppreference.com/w/cpp/language/floating_literal

    0 讨论(0)
提交回复
热议问题