在最新的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(boolean) 值,并且从不引发任何浮点异常。

简而言之:您只需要处理true / false就可以了。

参考资料:

Open Group的描述(不是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 标准:

    关于c++ - 何时使用C浮点比较功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59396641/

    10-11 22:48
    查看更多