用C/C++中的%f确定浮点数的输出(打印)

wha*_*cko 1 c c++ math floating-point

I have gone through earlier discussions on floating point numbers in SO but that didn't clarified my problem,I knew this floating point issues may be common in every forum but my question in not concerned about Floating point arithmetic or Comparison.I am rather inquisitive about its representation and output with %f.

问题很简单:"如何确定以下方面的确切输出:

float = <Some_Value>f;     
printf("%f \n",<Float_Variable>);
Run Code Online (Sandbox Code Playgroud)

让我们考虑一下这段代码:

float f = 43.2f,
f1 = 23.7f,
f2 = 58.89f,
f3 = 0.7f;

printf("f1 = %f\n",f);
printf("f2 = %f\n",f1);
printf("f3 = %f\n",f2);
printf("f4 = %f\n",f3);
Run Code Online (Sandbox Code Playgroud)

输出:

f1 = 43.200001
f2 = 23.700001
f3 = 58.889999
f4 = 0.700000
Run Code Online (Sandbox Code Playgroud)

我知道%f(意思是双倍)的默认精度为6,我也知道问题(在这种情况下)可以通过使用double修复,但我对输出f2 = 23.700001f3 = 58.889999浮点数好奇.

EDIT: I am aware that floating point number cannot be represented precisely, but what is the rule of for obtaining the closest representable value ?

谢谢,

ava*_*kar 6

假设您正在谈论IEEE 754 float,它具有24个二进制数字的精度:表示二进制(精确)的数字,并将数字四舍五入到第24个最高有效数字.结果将是最接近的浮点.

例如,23.7以二进制表示

10111.1011001100110011001100110011...
Run Code Online (Sandbox Code Playgroud)

四舍五入之后你就会得到

10111.1011001100110011010
Run Code Online (Sandbox Code Playgroud)

以十进制表示

23.700000762939453125
Run Code Online (Sandbox Code Playgroud)

四舍五入到小数点后六位,你就可以了

23.700001
Run Code Online (Sandbox Code Playgroud)

这正是你的输出printf.