在C%F说明的联合国predictable行为 [英] Unpredictable behaviour of %f specifier in c
问题描述
通过以下code:
With following code:
float f = 23.456;
printf("%f", f);
输出,适合的不同率F
是:
Value Output
--------- --------
f = 23.456 23.455999
f = 23.956 23.955999
f = 23.947 23.947001
f = 23.656 23.656000
为什么值获得的未predictable还是有规律可循?
Why is the value obtained unpredictable or there is a pattern?
推荐答案
这是因为 IEEE的754 32位浮点格式这是用来用C来存储浮点数。你有尾数转换为二进制,并存储在浮动
变量所需的4个字节的空间低23位。有时它是完全转换为精确的二进制,在其他时间,可能无法精确转换这样的数量的截短形式被存储,这是从存储器读取时,计算结果为稍微不同的值。
It is because of IEEE 754 32-bit floating point format which is used by C to store floating point numbers. The Mantissa you have is converted in binary and stored in lower 23 bits of 4-byte space required by float
variable. Sometimes it is completely convertible to exact binary, at other times it may not be exactly converted so a truncated form of the number is stored, which is when read from memory, evaluates to a slightly different value.
在mathemetics您使用值这个行为类似于 1/3
0.33或0.333取决于您的precision的要求。
This behaviour is similar as in mathemetics you use value of 1/3
as 0.33 or 0.333 depending on your requirement of precision.
请尝试使用:结果 F = 0.25;
或结果 F = -15.625;
或任何十进制值完全转换为二进制文件,你会得到正确的结果。
Try using:
f = 0.25;
or,
f = -15.625;
or, any decimal value exactly convertible to binary, you will get correct result.
这篇关于在C%F说明的联合国predictable行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!