Checking if a double (or float) is NaN in C++

后端 未结 21 2299
北恋
北恋 2020-11-22 05:10

Is there an isnan() function?

PS.: I\'m in MinGW (if that makes a difference).

I had this solved by using isnan() from , which doe

21条回答
  •  星月不相逢
    2020-11-22 05:32

    As comments above state a != a will not work in g++ and some other compilers, but this trick should. It may not be as efficient, but it's still a way:

    bool IsNan(float a)
    {
        char s[4];
        sprintf(s, "%.3f", a);
        if (s[0]=='n') return true;
        else return false;
    }
    

    Basically, in g++ (I am not sure about others though) printf prints 'nan' on %d or %.f formats if variable is not a valid integer/float. Therefore this code is checking for the first character of string to be 'n' (as in "nan")

提交回复
热议问题