浮点数和双精度数如何在C中存储相同数量的小数点? [英] How is that both float and double can store same number of decimal points in C?

查看:149
本文介绍了浮点数和双精度数如何在C中存储相同数量的小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码。 (C)



This is the code. (C)

float f  = 3.1415926535897932384626433832795;
double d = 3.1415926535897932384626433832795;
	
printf("float  = %.20f \n", f);
printf("double = %.20f \n", d);





根据维基百科文章,double的精度是浮动的2倍。但我得到的输出是这个。





According to wikipedia article, double has 2x precision than float. But the output I get is this.

float  = 3.14159274101257320000
double = 3.14159265358979310000





浮动和双重之间没有太大的区别,除了双倍已经舍入最后一位数。



如果浮点只有7位精度,这怎么可能?




我尝试过:





There isn't a big difference between float and double except the double has rounded the last digit.

How is this possible if float has only a 7 digits precision ?


What I have tried:

float f  = 3.1415926535897932384626433832795;
double d = 3.1415926535897932384626433832795;
	
printf("float  = %.20f \n", f);
printf("double = %.20f \n", d);

推荐答案

您已指定应打印小数点后的20位数。他们是。但这并不意味着这些数字是正确和有意义的。



您还注意到最后四位数是零。这是因为 double 具有该精度,并且 printf()函数将附加数字设置为零。 br />


两个打印值都有这16位数的原因来自 printf()函数支持 double 值作为浮点参数并传递 float 参数转换为 double 幕后。编译器将其处理为:

You have specified that 20 digits after the decimal point should be printed. And so they are. But that does not mean that these digits are correct and meaningful.

You have also noticed that the last four digits are zeroes. That is because a double has that precision and the additional digits are set to zero by the printf() function.

The reason that both printed values have these 16 digits is sourced by the fact that the printf() function only supports double values as floating point arguments and passed float arguments are converted to double behind the scenes. The compiler is processing it as:
printf("float  = %.20f \n", (double)f);



以适当分辨率打印的结果值为:


The resulting values printed with appropriate resolution are:

input  = 3.1415926535897932384626433832795
double = 3.14159265358979311
float  = 3.141592741

正如您所看到的那样, float 与第8位的输入和第17位的 double 不同数字。

As you can see the float differs from the input at the 8th digit and the double at the 17th digit.


如果 float 只有 7位精度,这怎么可能?



根据维基百科的文章,double的精度是浮动的2倍。但我得到的输出是这个。



float = 3.141592 74101257320000

double = 3.141592 65358979310000




(它仍然只有7位精度)。
How is this possible if float has only a 7 digits precision ?

According to wikipedia article, double has 2x precision than float. But the output I get is this.

float = 3.14159274101257320000
double = 3.14159265358979310000


(It still only has "7 digits of precision").


引用:

但那些错误的数字来自哪里?它们不应该在浮点数第7位之后是00000吗?

But where did those wrong numbers came from ? Shouldn't they be 00000 after 7th position in float?



这是因为这些值在内部存储为2的子幂并且值不准确。

请参阅: Pi和e In Binary - 探索二进制 [ ^ ]


这篇关于浮点数和双精度数如何在C中存储相同数量的小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆