如何在 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.