Float and double precision in C

2019-09-11 16:22发布

问题:

In C, double has more precision than float, and according to "C primerplus sixth edition" book (page 80), a float can represent at least 6 significant figures and a double can represent at least 13 significant figures. So I tried to verify that with this simple example:

#include<stdio.h>

int main(void){
    float a = 3.3333333; // 7 significant digits
    double b = 3.33333333333333;// 14 significant digits

    printf("\nFloat:  %f\n", a);
    printf("Double: %f\n", b);

    return 0;
} 

And this is the output of this program:

Float : 3.333333
Double: 3.333333

Why does the double value have the same precision as the float value, instead of displaying more significant digits?

回答1:

Most questions like this can be answered by consulting the C standard:

Each conversion specification is introduced by the '%' character ... after which the following appear in sequence:

...

  • An optional precision that gives ... the number of digits to appear after the radix character for the a, A, e, E, f, and F conversion specifiers.

Describing the f specifier:

The double argument shall be converted to decimal notation in the style "[-]ddd.ddd", where the number of digits after the radix character is equal to the precision specification. If the precision is missing, it shall be taken as 6.

So, by simply using %f, you are instructing printf to print six digits after the .. If you want to see more digits, you need to specify the precision: %.15f, for example.



回答2:

You need to show more significant digits. If you do this:

printf("\nFloat:  %.20f\n", a);
printf("Double: %.20f\n", b);

You'll get this:

Float:  3.33333325386047363281
Double: 3.33333333333332992865 


标签: c precision