在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP