printf和scanf如何处理浮点精度格式

printf和scanf如何处理浮点精度格式

本文介绍了printf和scanf如何处理浮点精度格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码片段:

float val1 = 214.20;
double val2 = 214.20;

printf("float : %f, %4.6f, %4.2f \n", val1, val1, val1);
printf("double: %f, %4.6f, %4.2f \n", val2, val2, val2);

哪些输出:

float : 214.199997,  214.199997, 214.20 | <- the correct value I wanted
double: 214.200000,  214.200000, 214.20 |

我明白 214.20 有一个无限二进制表示。第一行的前两个元素具有预期值的近似值,但最后一个似乎根本没有近似值,这导致了以下问题:

I understand that 214.20 has an infinite binary representation. The first two elements of the first line have an approximation of the intended value, but the the last one seems to have no approximation at all, and this led me to the following question:

如何执行 scanf fscanf printf fprintf (等)功能处理精度格式?

How do the scanf, fscanf, printf, fprintf (etc.) functions treat the precision formats?

无精度提供, printf 打印出近似值,但是使用%4.2f 它给出了正确的结果。你能解释一下这些函数用来处理精度的算法吗?

With no precision provided, printf printed out an approximated value, but with %4.2f it gave the correct result. Can you explain me the algorithm used by these functions to handle precision?

推荐答案

事情是,214.20不能表达正确地二进制表示。很少的十进制数可以。因此存储一个近似值。现在当你使用printf时,二进制表示形式变成一个十进制表示形式,但是它再也不能被精确地表达,而且只是近似的。

The thing is, 214.20 cannot be expressed exactly with binary representation. Few decimal numbers can. So an approximation is stored. Now when you use printf, the binary representation is turned into a decimal representation, but it again cannot be expressed exactly and is only approximated.

如你所知,你可以给出printf的精度告诉它如何舍入十进制近似。如果你不给它一个精度,那么假定精度为6(详见手册页)。

As you noticed, you can give a precision to printf to tell it how to round the decimal approximation. And if you don't give it a precision then a precision of 6 is assumed (see the man page for details).

如果你使用 %.40f 为float和%.40lf 为您的示例中的双倍,您将得到这些结果:

If you use %.40f for the float and %.40lf for the double in your example above, you will get these results:

214.1999969482421875000000000000000000000000
214.1999999999999886313162278383970260620117

他们是不同的,因为双重的,有更多的位来更好地约214.20。但是正如你所看到的,他们仍然非常奇怪,以十进制表示。

They are different because with double, there are more bits to better approximate 214.20. But as you can see, they are still very odd when represented in decimal.

我建议阅读,了解有关浮点数如何工作的更多见解。一个很好的阅读也是每个计算机科学家应该知道的关于浮点运算的一些

I recommend to read the Wikipedia article on floating point numbers for more insights about how floating point numbers work. An excellent read is also What Every Computer Scientist Should Know About Floating-Point Arithmetic

这篇关于printf和scanf如何处理浮点精度格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:07