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

后端 未结 21 1864
北恋
北恋 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:45

    First solution: if you are using C++11

    Since this was asked there were a bit of new developments: it is important to know that std::isnan() is part of C++11

    Synopsis

    Defined in header

    bool isnan( float arg ); (since C++11)
    bool isnan( double arg ); (since C++11)
    bool isnan( long double arg ); (since C++11)
    

    Determines if the given floating point number arg is not-a-number (NaN).

    Parameters

    arg: floating point value

    Return value

    true if arg is NaN, false otherwise

    Reference

    http://en.cppreference.com/w/cpp/numeric/math/isnan

    Please note that this is incompatible with -fast-math if you use g++, see below for other suggestions.


    Other solutions: if you using non C++11 compliant tools

    For C99, in C, this is implemented as a macro isnan(c)that returns an int value. The type of x shall be float, double or long double.

    Various vendors may or may not include or not a function isnan().

    The supposedly portable way to check for NaN is to use the IEEE 754 property that NaN is not equal to itself: i.e. x == x will be false for x being NaN.

    However the last option may not work with every compiler and some settings (particularly optimisation settings), so in last resort, you can always check the bit pattern ...

提交回复
热议问题