开发者

How to check for inf (and | or) NaN in a double variable

Consider t开发者_如何学Pythonhe following code:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

template<class T>
bool IsNaN(T t)
{
    return t != t;
}

int main(int argc, char**argv)
{
    double d1, d2;
    sscanf(argv[1], "%f", &d1);
    sscanf(argv[2], "%f", &d2);

    double dRes = d1/d2;

    cout << "dRes = " << dRes << "\n";

    if(IsNaN(dRes))
        cout << "Is NaN\n";
    else
        cout << "Not NaN\n";

}

Couple of questions:

  1. When I pass 0 and 0 as arguments, it outputs dRes = inf. But I was expecting dRes = NaN or something like that.
  2. Is NaN representable in double variables? For that matter, any variable?
  3. When I changed the data type of d1,d2,dRes to int and passed 0 and 0, I got a Floating exception. What is the difference?
  4. How to check if a variable's value is equal to inf?


  1. When using scanf() double should be read using %lf, not %f. %f will convert the input into a 32-bit float, so the first 32 bits of your variables will be filled with some invalid data, and the last 32 bits will be left as garbage.

  2. Yes. #include <limits>, then std::numeric_limits<double>::quiet_NaN(). Some compilers (e.g. gcc) also provides the NAN macro in <cmath>.

  3. There is no NaN or infinity for integer types. Divide-by-zero for integer will cause an exception (SIGFPE).

  4. #include <cmath>, then std::isinf(x). Use std::isfinite(x) to ensure x is not NaN or Infinity.


The function fpclassify will let you inspect a floating-point value for all the special cases.

It's found in <math.h> as a macro since C99, and in <cmath> as a family of functions, for float, double, and long double under the overloaded name std::fpclassify since C++11.

cppreference has a nice example


Just do it like that:

if (dRes  == +1.0/0.0 || dRes  == -1.0/0.0) ... //+INF, -INF
if (dRes  == +0.0/0.0 ) ... //+NaN; i.e. pow(2.0 ,16384.0)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜