今天做一个实验的时候,莫名其妙地出错。。。
然后不断地DEBUG,最后居然发现下面问题:
float check1=33359568.000,check2=272322.000;
printf("%f\n",check1+check2);
在GCC下可以输出正确结果33631890.000,但是在VS2012下,结果却是33631888.000!!!
知道怎么回事的可以回复或者在http://social.msdn.microsoft.com/Forums/en-US/80ca3c69-c78b-44f2-bf71-80e01bb9f0e3/it-is-a-bug-in-vs2012-c-compiler-of-float-add-operation?forum=msbuild 这里回答我的问题,谢谢。
答案就是精度的问题:
引自 Anna Cc 的回答
I suggest you read this thread,
Difference between float and double
As the name implies, a double
has 2x the precision of float
<sup>[1]</sup>. In general a double has 15 to 16 decimal digits of precision, while float
only has 7.
This precision loss could lead to truncation errors much easier to float up.
"don't use +=
to sum lots of floating point numbers as the errors accumulate quickly."
The C and C++ standards do not specify the representation of float
, double
and long double
. It is possible that all three implemented as IEEE double-precision. Nevertheless, for most architectures (gcc, MSVC; x86, x64, ARM) float
is indeed a IEEE single-precision floating point number (binary32), and double
is a IEEE double-precision floating point number (binary64).