gpt4 book ai didi

c - C中的 float 和 double

转载 作者:太空宇宙 更新时间:2023-11-04 05:09:10 26 4
gpt4 key购买 nike

在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 值具有相同的精度,而不是显示更多有效数字?

最佳答案

像这样的大多数问题都可以通过查阅 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 - C中的 float 和 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32291052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com