我希望在某些double
值为NaN
或#INF
时隔离该行为。要检测NaN
,我测试
doubleVal != doubleVal
#INF
怎么样?当doubleVal
是#INF
?
答案 0 :(得分:4)
一旦你确定它不是1.
,乘以NaN
怎么样?
您也可以使用isinf
和isnan
,但这些可能会产生一些开销,具体取决于其实施方式。
第三种方法是使用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);