简体   繁体   English

C语言中的浮点数和双精度

[英]Float and double precision in C

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. 在C语言中,双精度比浮点数更精确,根据“ C Primerplus第六版”书(第80页),浮点数可以表示至少6个有效数字,而双精度数可以表示至少13个有效数字。 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? 为什么double值与float值具有相同的精度,而不显示更多的有效数字?

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 

Most questions like this can be answered by consulting the C standard: 可以通过参考C标准来回答大多数此类问题:

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. 一个可选的精度,它为a,A,e,E,f和F转换说明符提供...在基数字符后出现的位数。

Describing the f specifier: 描述f说明符:

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. double参数应转换为“ [-] ddd.ddd”格式的十进制表示法,其中基数字符后的位数等于精度规范。 If the precision is missing, it shall be taken as 6 . 如果缺少精度,则应取为6

So, by simply using %f , you are instructing printf to print six digits after the . 因此,仅使用%f即可指示printf.之后打印六位数字. . If you want to see more digits, you need to specify the precision: %.15f , for example. 如果要查看更多数字,则需要指定精度:例如%.15f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM