关于c中 int, float, double转换中存在的精度损失问题

先看一段代码实验:

#include<limits>
#include<iostream>

using namespace std;

int main()
{
    unsigned int i = numeric_limits<unsigned int >::max();
    float f = i;
    unsigned int j = (unsigned int )f;
    bool flag 1 = i==j;
    cout<<"i = "<<endl;
    cout<<"j = "<<endl;
    cout<<"flag1 = " <<flag1<<endl;

   
   double d = 0.6L; // change this value  to 0.5L, you will see different result
   float e = (float)d;
   double d2 = e;
   bool flag2 = d==d2;
  cout<<"d2: "<<d2<<endl;
  cout<<"d: "<<d<<endl;
  cout<<"flag2: "<<flag2<<endl;

}

 从这个例子中可以看出flag1和flag2均为flase,且虽然d2和d在输出的时候虽然看上去一致,但实际并不相等;而i与j的实际值就已经查了很远。具体原因参见参考文献[1]。

深层原理分析还需进一步学习中。 。。。。待补充。

 

Reference

[1]int, float, double之间不得不说的故事, http://www.cnblogs.com/wodehuajianrui/archive/2009/03/18/1415173.html

posted @ 2014-05-20 14:30  jiayouwyhit  阅读(3407)  评论(0编辑  收藏  举报