c - C中的 float 和 double

标签 c precision

在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/

相关文章:

c++ - 如何计算精度为 E=0.0001 的序列 e^(-x) 之和?

c - 链接期间的 GCcflags

c - 从 c 中的结构读取/写入

c - 将具有不同数据类型的文本文件放入结构数组

c++ - round 函数返回错误的双重估计

math - float 学有问题吗?

c - 编写递归字符串反向器 我的较小输入是什么?

c - 根据 C11,什么是 "byte"?

math - float 学有问题吗?

c++ - 将数字从字符串流转换为具有设定精度的字符串