C语言中的浮点数和双精度 [英] Float and double precision in C
问题描述
在C语言中,双精度数比浮点数更精确,根据"C Primerplus第六版"书(第80页),浮点数可以表示至少6个有效数字,而双精度数可以表示至少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;
}
这是该程序的输出:
Float : 3.333333
Double: 3.333333
为什么double值与float值具有相同的精度,而不显示更多的有效数字?
Why does the double value have the same precision as the float value, instead of displaying more significant digits?
推荐答案
可以通过参考C标准来回答大多数此类问题:
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:
...
- 一种可选的精度,它给出...在a,A,e,E,f和F转换说明符的基数字符后出现的位数.
描述f
说明符:
双精度参数应转换为"[-] ddd.ddd"格式的十进制表示法,其中基数字符后的位数等于精度规范. 如果精度丢失,则应取为6 .
因此,只需使用%f
,即指示printf
在.
之后打印六位数字.如果要查看更多数字,则需要指定精度:例如%.15f
.
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.
这篇关于C语言中的浮点数和双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!