How to produce a NaN float in c?

前端 未结 9 937
春和景丽
春和景丽 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:48

    You can either use NAN macro, or simply one of nan/nanf functions to assign a nan value to a variable.
    to check if you are dealing with a nan value, you can use isnan(). Here is an example:

    #include 
    #include 
    
    int main(void) {
    
        float a = NAN;//using the macro in math.h
        float f = nanf("");//using the function version 
        double d = nan("");//same as above but for doubles!
    
        printf("a = %f\nf = %f\nd = %f\n",a,f,d);
    
        if(isnan(a))
            puts("a is a not a number!(NAN)\n");
    
        return 0;
    }
    

    Running the code snippet above will give you this output:

    a = nan
    f = nan
    d = nan
    a is a not a number!(NAN)
    

    Run the code yourself : http://ideone.com/WWZBl8
    read more information : http://www.cplusplus.com/reference/cmath/NAN/

提交回复
热议问题