C float behavior

#include<stdio.h>
int main()
{
   float f = 0.1;
   double d = 0.1;
   printf("%lu %lu %lu %lu\n", sizeof(f), sizeof(0.1f), sizeof(0.1), sizeof(d));
   return 0;
}

Exit

$ ./a.out 
4 4 8 8

As in the previous code, we can see that sizeof(0.1)they sizeof(0.1f)do not match. sizeof(0.1) is 8 bytes, a sizeof(0.1f) is 4 bytes. but when assigned, value to float variable fit automatically trims its size to 4 bytes.

While in the code below when comparing with float x it is not cropped and 4 bytes of floatcompared with 8 bytes of 0.1, the value is the float xsame 0.1fas since both have 4 bytes.

#include<stdio.h>
int main()
{
    float x = 0.1;
    if (x == 0.1)
        printf("IF");
    else if (x == 0.1f)
        printf("ELSE IF");
    else
        printf("ELSE");
}

Exit

$ ./a.out 
ELSE IF

why and how does it truncate when assigned, and not when compared?

+4
source share
5 answers

A floating point literal without a suffix is ​​of type double. The suffix with fmakes a literal type float.

= , .

== , x == 0.1 (double)x == 0.1, , (double)(float)0.1 0.1 - , x == 0.1f float, .

, .

+8

0.1f ( "f" ) float, , , float, double. 0,1 0,1, 0,1f

+2

, 0.1, , float, 0.1f.

float f = 0.1;

0.1 .

float x = 0.1;
if (x == 0.1)

, x double, , , . double x = 0.1;

+2

0.1, double. f .

float ieee standard, else if, 0.1f double .

https://en.wikipedia.org/wiki/Floating_point

+1

0.1 , 0.1f . , float x=0.1, double x=0.1, .

f, .

-

if(x == 0.1)

flase, 0.1 0.1 . i.e double.

float, double , double , float, .

+1

Source: https://habr.com/ru/post/1608137/


All Articles