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

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

    It seems to me that the best truly cross-platform approach would be to use a union and to test the bit pattern of the double to check for NaNs.

    I have not thoroughly tested this solution, and there may be a more efficient way of working with the bit patterns, but I think that it should work.

    #include 
    #include 
    
    union NaN
    {
        uint64_t bits;
        double num;
    };
    
    int main()
    {
        //Test if a double is NaN
        double d = 0.0 / 0.0;
        union NaN n;
        n.num = d;
        if((n.bits | 0x800FFFFFFFFFFFFF) == 0xFFFFFFFFFFFFFFFF)
        {
            printf("NaN: %f", d);
        }
    
        return 0;
    }
    

提交回复
热议问题