浮点型数据转整型的丢失精度问题(C++)

如下代码:http://ideone.com/xcgHgw

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int i = 0;
    i = 9.0 * 0.6 + 0.6;
    cout << i << endl;
    
    i = 9.0 * 0.6 + 0.6;
    cout << i << endl;
    
    i = (double)(9.0 * 0.6 + 0.6);
    cout << i << endl;
    
    cout << (double)(9.0 * 0.6 + 0.6);
    return 0;
}

本意是打印4个6;

但是打印结果是:

5

5

5

6;

原因是

9.0 * 0.6的返回值很有可能是5.3999...,+ 0.6后是5.9999...;强制转换为int型后是5;

解决方案是:

不要将double型的数据赋给整型,否则可能出现与初衷不符。

 

posted on 2017-05-16 19:21  _bob  阅读(2410)  评论(0编辑  收藏  举报