簡介
兩個浮點數不能直接使用 == 來確定相等,因為浮點數精度可能導致微小的誤差
方法一:
使用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; }