0
#include<stdio.h>
int main()
{
 float f = 0.1;
        if (f == 0.1)
            printf("True");
        else
            printf("False");
  return 0;
}

The above code is given in my class test. I was expecting true as the output but False was the output. WHy?

jai deep
  • 33
  • 1
  • 5
  • 3
    because `0.1` has type `double` and `0.1f != 0.1` ... `float fx = 1.0/10; double dx = 1.0/10; printf("%d\n", dx == fx);` If you compare with `float` you get what you expect: `if (f == 0.1f)` or `if (f == (float)0.1)` – pmg Nov 17 '19 at 16:21
  • 2
    Suggestion: **always** (yes, always) use `double` when you want to work with floating-point values. – pmg Nov 17 '19 at 16:24

1 Answers1

-1

In c language a float variable contain by default 7 decimals but you compare it with only one decimal in your if check. you can write f after decimal value to represent all decimals. Now it will answers True.

Like this:

#include<stdio.h>
int main()
{
 float f = 0.1;
        if (f == 0.1f)
            printf("True");
        else
            printf("False");
  return 0;
}
Sheri
  • 1,383
  • 3
  • 10
  • 26