在最新的 C++ 标准中,我注意到以下宏:
bool isgreater(float x, float y);
bool isgreaterequal(float x, float y);
bool isless(float x, float y);
bool islessequal(float x, float y);
bool islessgreater(float x, float y);
bool isunordered(float x, float y);
这些宏来自 C(7.12.14 和 7.12.14)。
那么,为什么有人会使用这些宏而不是运算符呢?这些宏有什么特别之处吗(比如检查
inf
),还是它们与对应的运算符相同?C++ 示例:
#include <iostream>
#include <cmath>
int main()
{
float x=0.2;
float y=0.5;
std::cout << x << " < " << y << " : " << std::boolalpha << std::islessequal( x, y ) << std::endl;
std::cout << x << " < " << y << " : " << std::boolalpha << ( x <= y ) << std::endl;
}
最佳答案
与关系运算符不同,这些宏实际上只返回一个 bool 值,并且从不引发任何浮点异常。
简而言之:您只需处理true
/false
没有别的了。
引用:
公开组 描述(不是 C 或 C++ 标准,但与 Unix/Linux 世界高度相关,几乎总是与标准相似):
C++ 标准:
C Library [c.math]:
The classification/comparison functions behave the same as the C macros with the corresponding names defined in 7.12.3, Classification macros, and 7.12.14, Comparison macros in the C Standard. Each function is overloaded for the three floating-point types, as follows [...]
中号标准:
7.12.14 Comparison macros
[...] For any ordered pair of numeric values exactly one of the relationships — less, greater, and equal — is true. Relational operators may raise the ‘‘invalid’’ floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. The following subclauses provide macros that are quiet (non floating-point exception raising) versions of the relational operators, and other comparison macros that facilitate writing efficient code that accounts for NaNs without suffering the ‘‘invalid’’ floating-point exception. In the synopses in this subclause, real-floating indicates that the argument shall be an expression of real floating type.
关于c++ - 何时使用 C 浮点比较函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59396641/