-1

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Shubhansu kumar
  • 89
  • 1
  • 1
  • 10

3 Answers3

1

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;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
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

Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27
0

0.100000 is double by default, try 0.100000f. if you need to compare with double, you need to try something described here.

Afshin
  • 8,839
  • 1
  • 18
  • 53