C++ - 比较两个浮点数大小

简介

两个浮点数不能直接使用  == 来确定相等,因为浮点数精度可能导致微小的误差

 

方法一:

使用std::abs()函数来比较两个浮点数的差值是否小于一个非常小的阈值

float a = 1.5;
float b = 2.3;
float epsilon = 1e-9;
 
if (std::abs(a - b) < epsilon) {
    cout << "a is equal to b" << endl;
} else if (a < b) {
    cout << "a is less than b" << endl;
} else {
    cout << "a is greater than b" << endl;
}

 

方法二:

使用std::numeric_limits<float>::epsilon()函数来比较两个浮点数的差值是否小于浮点数类型的最小可表示差值

#include <limits>
 
float a = 1.5;
float b = 2.3;
 
if (std::abs(a - b) < std::numeric_limits<float>::epsilon()) {
    cout << "a is equal to b" << endl;
} else if (a < b) {
    cout << "a is less than b" << endl;
} else {
    cout << "a is greater than b" << endl;
}

 

posted @ 2024-05-25 14:13  Citrusliu  阅读(544)  评论(0编辑  收藏  举报