如何在 C++ 中比較浮點數和雙精度浮點數?


比較浮點數和雙精度浮點變數取決於你的最終目標。如果你希望獲得一個可執行的函式,而不用去過分了解細節,並且對一些不準確的計算結果沒有問題,你可以使用以下函式:

示例

#include<iostream>
using namespace std;

// Define the error that you can tolerate
#define EPSILON 0.000001

bool areSame(double a, double b) {
   return fabs(a - b) < EPSILON;
}

int main() {
   double a = 1.005;
   double b = 1.006;
   cout << areSame(a, a);
   cout << areSame(a, b);
}

輸出

這個輸出如下:

1
0

此函式採用你的錯誤容差,檢查閾值是否大於你要比較的數字之間的差。如果你需要更精確的東西,最好閱讀這篇優秀的部落格文章:https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

更新日期:2020 年 6 月 24 日

631 次瀏覽

開啟你的 職業 生涯

完成課程可獲得認證

入門指南
廣告
© . All rights reserved.