What's the use of suffix `f` on float value

前端 未结 7 600
失恋的感觉
失恋的感觉 2020-11-28 04:25

I am wondering what the difference is between these two variables in C:

float price = 3.00;

and

float price = 3.00f;
         


        
7条回答
  •  眼角桃花
    2020-11-28 05:25

    Because by unsuffixed floating-point literals are doubles, and rounding means that even small literals can take on different values when rounded to float and double. This can be observed in the following example:

    float f=0.67;
    if(f == 0.67) 
      printf("yes");
    else 
      printf("no");  
    

    This will output no, because 0.67 has a different value when rounded to float than it does when rounded to double. On the other hand:

    float f=0.67;
    if(f == 0.67f) 
      printf("yes");
    else 
      printf("no"); 
    

    outputs yes.

    The suffix can be specified using either upper or lowercase letters.

    Try this also:

    printf(" %u %u\n", sizeof(.67f), sizeof(.67));
    

    Check @codepade

提交回复
热议问题