Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"==" operator seeems not to work for floating point numbers

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading