如何在 C++ 中比較 float 和 double?


比較浮點數和 double 變數取決於你的最終目標是什麼。如果想要一個可執行的函式,無需過多深入瞭解詳情,並且一些不準確的計算不會造成問題,可以使用以下函式 −

示例

#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 日

632 次瀏覽

開啟你的職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.