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
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP