"==" operator seeems not to work for floating point numbers [duplicate]

Can someone please explain the output here?

#include <stdio.h>

int main(void) {
    float f = 0.1 ;
    printf ("%f\n",f ) ;
    if (f == 0.100000) {
        printf ("true ") ;
    }
    else {
        printf ("False") ;
    }
    return 0;
}

output:

0.100000
False

Solution 1:

You are trying to compare a float number with a double. The number 0.100000is considered as doubletype unless you specify with a trailing f that it is a float. Thus:

int main(){
    float x = 0.100000;
    if (x == 0.100000)
        printf("NO");
    else if (x == 0.100000f)
        // THE CODE GOES HERE
        printf("YES");
    else
        printf("NO");
}

You mat refer to single precision and double precision for theoritical details

Solution 2:

Objects of the types float and double are stored with different precisions.

You should write

 if (f == 0.100000f) {

trying to compare two floats.

Also it would be better to initialize the variable f with a constant of the type float

float f = 0.1f;