浮點數的比較 C++
用 “==” 來比較浮點數。返回的數是不確定的。計算機對浮點數的進行計算的原理是隻保證必要精度內正確即可。
我們在判斷浮點數相等時,推薦用範圍來確定,若x在某一範圍內,我們就認爲相等,至於範圍怎麼定義,要看實際情況而已了,float,和double 各有不同
例子
#include <iostream>
#include <bitset>
#include <algorithm>
using namespace std;
int main(){
double d1 = 3.141592654141592654;
double d2 = 3.141592654141592644;
double rang = 0.0001;
cout<<d1<<", "<<d2<<endl;
// 運行結果是 equals,這是錯誤的
if (d1 == d2) {
cout<<"equals"<<endl;
}
else {
cout<<"Not equals"<<endl;
}
double x = d1 - d2;
// 運行結果是 Not equals 。
if ( x >= rang && x <= rang ) {
cout<<"equals"<<endl;
}
else {
cout<<"Not equals"<<endl;
}
return 0;
}