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
}
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;
}
}输出结果
They are equivalent They are not equivalent