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

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

    You can use numeric_limits::quiet_NaN( ) defined in the limits standard library to test with. There's a separate constant defined for double.

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main( )
    {
       cout << "The quiet NaN for type float is:  "
            << numeric_limits::quiet_NaN( )
            << endl;
    
       float f_nan = numeric_limits::quiet_NaN();
    
       if( isnan(f_nan) )
       {
           cout << "Float was Not a Number: " << f_nan << endl;
       }
    
       return 0;
    }
    

    I don't know if this works on all platforms, as I only tested with g++ on Linux.

提交回复
热议问题