gpt4 book ai didi

c++ - 何时使用 C 浮点比较函数?

转载 作者:IT老高 更新时间:2023-10-28 12:34:30 25 4
gpt4 key购买 nike

在最新的 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 即可。


引用文献:

The Open Group 描述(不是 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 [...]

C标准:

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/11826314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com