C中的浮点数和双精度
Float and double precision in C
在 C 中,double 比 float 更精确,根据 "C primerplus sixth edition" 书(第 80 页),float 至少可以表示 6 位有效数字,double 可以表示至少 13 位有效数字。所以我试着用这个简单的例子来验证:
#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;
}
这是这个程序的输出:
Float : 3.333333
Double: 3.333333
为什么double值与float值的精度相同,而不是显示更多有效数字?
您需要显示更多有效数字。如果你这样做:
printf("\nFloat: %.20f\n", a);
printf("Double: %.20f\n", b);
你会得到这个:
Float: 3.33333325386047363281
Double: 3.33333333333332992865
像这样的大部分问题都可以通过查阅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.
描述 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. If the precision is missing, it shall be taken as 6.
因此,只需使用 %f
,您就可以指示 printf
在 .
之后打印六位数字。如果要查看更多的数字,需要指定精度:例如%.15f
。
在 C 中,double 比 float 更精确,根据 "C primerplus sixth edition" 书(第 80 页),float 至少可以表示 6 位有效数字,double 可以表示至少 13 位有效数字。所以我试着用这个简单的例子来验证:
#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;
}
这是这个程序的输出:
Float : 3.333333
Double: 3.333333
为什么double值与float值的精度相同,而不是显示更多有效数字?
您需要显示更多有效数字。如果你这样做:
printf("\nFloat: %.20f\n", a);
printf("Double: %.20f\n", b);
你会得到这个:
Float: 3.33333325386047363281
Double: 3.33333333333332992865
像这样的大部分问题都可以通过查阅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.
描述 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. If the precision is missing, it shall be taken as 6.
因此,只需使用 %f
,您就可以指示 printf
在 .
之后打印六位数字。如果要查看更多的数字,需要指定精度:例如%.15f
。