How to produce a NaN float in c?

前端 未结 9 945
春和景丽
春和景丽 2020-12-05 14:01
float f = (float)\'a\';
if(f < 0){ 
}   
else if(f == 0){ 
}   
else if(f > 0){ 
}   
else{
    printf(\"NaN\\n\");                                                     


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 14:41

    Using floating point numbers, 0.0 / 0.0 isn't a "divide by zero" error; it results in NaN.

    This C program prints -nan:

    #include 
    
    int main()
    {
        float x = 0.0 / 0.0;
        printf("%f\n", x);
        return 0;
    }
    

    In terms what NaN looks like to the computer, two "invalid" numbers are reserved for "signaling" and "quiet" NaN (similar to the two invalid numbers reserved for positive and negative infinity). The Wikipedia entry has more details about how NaN is represented as an IEE floating point number.

提交回复
热议问题