c ++测试double是否为#INF

时间:2012-04-12 09:09:42

标签: c++ double nan

我希望在某些double值为NaN#INF时隔离该行为。要检测NaN,我测试

doubleVal != doubleVal

#INF怎么样?当doubleVal#INF

时,此测试是否属实?

3 个答案:

答案 0 :(得分:4)

一旦你确定它不是1.,乘以NaN怎么样?

http://ideone.com/97FNu

您也可以使用isinfisnan,但这些可能会产生一些开销,具体取决于其实施方式。

第三种方法是使用C max值宏(或等效的std::numeric_limits):

 bool is_inf_or_nan(double x) 
{
    return !(x <= DBL_MAX && x >= -DBL_MAX); 
}    

答案 1 :(得分:3)

如果你没有使用c ++ 11,那么你需要<boost/math/special_functions/fpclassify.hpp>而不是<cmath>,并且相应的命名空间会有所改变。

#include <cmath> // or <boost/math/special_functions/fpclassify.hpp>
// ...

    if(isinf(num)){
        // ...
    }

答案 2 :(得分:3)

Boost中还有一个header-only library,它具有处理浮点数据类型的简洁工具

#include <boost/math/special_functions/fpclassify.hpp>

您将获得以下功能:

template <class T> bool isfinite(T z);
template <class T> bool isinf(T t);
template <class T> bool isnan(T t);
template <class T> bool isnormal(T t);