码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-05-22 00:48:31      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   c   code   http   

先看一段代码实验:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#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;
 
    
 <span style="color: rgb(255, 0, 0);"> <strong> double d = 0.6L; // change this value  to 0.5L, you will see different result
</strong></span>   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

关于c中 int, float, double转换中存在的精度损失问题,布布扣,bubuko.com

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

标签:style   blog   class   c   code   http   

原文地址:http://www.cnblogs.com/jiayouwyhit/p/3738884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!