在 C/C++ 中,浮點數和雙精度數的比較,哪種方法最有效?


在這裡,我們將瞭解如何使用 C 或 C++ 比較兩個浮點數資料或兩個雙精度數資料。浮點數/雙精度數比較與整數比較不同。

要比較兩個浮點數或雙精度值,我們必須在比較中考慮精度。例如,如果兩個數字是 3.1428 和 3.1415,那麼它們在精度 0.01 內是相同的,但是在精度 0.001 就不相同。

要使用這個標準進行比較,我們將從一個浮點數中減去另一個浮點數,找到絕對值,然後檢查結果是否小於精度值。透過這種方式,我們可以判斷它們是否相等。

示例

#include <iostream>
#include <cmath>
using namespace std;
bool compare_float(float x, float y, float epsilon = 0.01f){
   if(fabs(x - y) < epsilon)
      return true; //they are same
      return false; //they are not same
}
bool compare_float(double x, double y, double epsilon = 0.0000001f){
   if(fabs(x - y) < epsilon)
      return true; //they are same
      return false; //they are not same
}
int main() {
   float x, y;
   x = 22.0f/7.0f;
   y = 3.1415f;
   if(compare_float(x, y)){
      cout << "They are equivalent" << endl;
   } else {
      cout << "They are not equivalent" << endl;
   }
   if(compare_float(x, y, 0.001f)){
      cout << "They are equivalent" << endl;
   } else {
      cout << "They are not equivalent" << endl;
   }
   double a, b;
   a = 2.03547415;
   b = 2.03547428;
   if(compare_float(a, b)){
      cout << "They are equivalent" << endl;
   } else {
      cout << "They are not equivalent" << endl;
   }
   if(compare_float(a, b, 0.000001f)){
      cout << "They are equivalent" << endl;
   } else {
      cout << "They are not equivalent" << endl;
   }
}

輸出

They are equivalent
They are not equivalent
They are not equivalent
They are equivalent

更新日期:2019 年 7 月 30 日

超過 7,000 次瀏覽

開啟你的職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.