Float and double precision in C

限于喜欢 提交于 2019-12-25 06:52:13

问题


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 


来源:https://stackoverflow.com/questions/32291052/float-and-double-precision-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!