2. float 的值的运算
c++ primier plus中有一段关于float运算的代码:
float a = 2.34E+22f;
float b = a + 1.0f;
cout << "a =" << a <<endl;
cout << "b -a =" << b - a<< endl;
结果是:
a =2.34e+22
b - a =0
这是为什么呢?
The single precision floating point type float
is like this(assuming IEEE-754)
m*2^e
where m
is a number between 223 and 224,and e
is an integer. 从上图来看,m的最大值是 223
#最大16777215# and e的最大值是 28
float在保存是会被rounded到最接近这个float的数值。 So the value 2.34e+22
is actually rounded to
10391687*251, which is 23399998850475413733376. This is the value of a
.
再有,float的运算结果也会被rounded到最接近的float数值。 if you add 1 to a
, the result is
23399998850475413733377, which is again rounded to the nearest floating-point number, which is still, of course,
23399998850475413733376. So b
gets the same value as a
. Since both numbers are equal, a
.
- b == 0