在这里,我们将看到如何使用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