如下代碼: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型的數據賦給整型,否則可能出現與初衷不符。