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

标签 c++ c c++11

在最新的 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 世界高度相关,几乎总是与标准相似):

  • http://pubs.opengroup.org/onlinepubs/009695399/functions/islessgreater.html
  • http://pubs.opengroup.org/onlinepubs/009695399/functions/isgreater.html
  • http://pubs.opengroup.org/onlinepubs/009695399/functions/isgreaterequal.html
  • http://pubs.opengroup.org/onlinepubs/009695399/functions/isless.html
  • http://pubs.opengroup.org/onlinepubs/009695399/functions/islessequal.html
  • http://pubs.opengroup.org/onlinepubs/009695399/functions/islessgreater.html
  • http://pubs.opengroup.org/onlinepubs/009695399/functions/isunordered.html

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

    相关文章:

    c++ - 在 NULL 指针上调用 delete - C++03 与 C++11

    c++ - 即使没有新数据,FD_ISSET 也始终为真?

    C++模板代码顺序解析/CRTP

    c - 如何将数组中的数字更改为符号

    c++ - 防止在头文件之外创建子类

    c++ - 使用删除使我的计算机崩溃

    c - 在 C 语言中,宏是否比全局变量运行得更快?如何在运行之间更改宏?

    C - 在递归函数 remove() 中不起作用

    c++ - 匹配模板别名作为模板模板参数

    c++ - 在 Linux 中构建 C++11 线程翻译单元