sizeof long double and precision not matching?

前端 未结 4 1553
攒了一身酷
攒了一身酷 2020-12-19 03:20

Consider the following C code:

#include 
int main(int argc, char* argv[]) 
{
    const long double ld = 0.12345678901234567890123456789012345L         


        
4条回答
  •  醉酒成梦
    2020-12-19 03:45

    Various C implementations of the long double may have variant range and precision. The sizeof hints to the underlying floating point notation, but does not specify it. A long double is not required to have 33 to 36 decimals. It could even have exactly the same representation as a double.

    Without hard-coding the precision, but using all the available precision and not overdoing it, recommend:

    const long double ld = 0.12345678901234567890123456789012345L;
    printf("%.*Le\n", LDBL_DIG + 3, ld);
    printf("%.*Le\n", LDBL_DIG + 3, nextafterl(ld, ld*2));
    

    This prints out (on my eclipse intel 64-bit), of course, yours may differ.

    1.234567890123456789013e-01
    1.234567890123456789081e-01
    

    [Edit]

    On review, a +2 is sufficient. Better to use LDBL_DECIMAL_DIG. see Printf width specifier to maintain precision of floating-point value

    printf("%.*Le\n", (LDBL_DIG + 3) - 1, ld);
    printf("%.*Le\n", LDBL_DECIMAL_DIG - 1, ld);
    

提交回复
热议问题