How to produce a NaN float in c?

前端 未结 9 940
春和景丽
春和景丽 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条回答
  •  猫巷女王i
    2020-12-05 14:47

    A -nan can also be produced by setting all 32 bits of a float variable as 1, as shown below:

    float nan_val = 0xffffffff;
    

    Also, you can compare if a float variable is -nan explicitly by checking if comparison with itself fails.

    if (nan_val != nan_val) {
    // executes iff nan_val is -nan
    }
    

    This method of comparison should work for compilers that use IEEE floats.

提交回复
热议问题