0
float a = 0.5;
float b = 0.7;
printf("%f",a);
printf("\n");
printf("%f",b);
if(a == .5)
  printf("\nOK\n");
else
   printf("NOTOK\n");

if(b == .7)
  printf("OK");
else
  printf("NOTOK");

It seems that output should be OK for both a and b but the output is OK for a but NOTOK for b. Why?

abcdxyzw
  • 9
  • 4
  • 7
    You've declared `b` as `float`, which is smaller than the default floating point type (`double`), so you're comparing `(float) 0.7` to `(double) 0.7)`. Since `0.7` cannot be exactly represented, they are not the same. Try replacing all your `float` variables with `double`. – Tom Karzes Oct 18 '17 at 03:54
  • https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Retired Ninja Oct 18 '17 at 03:55
  • Also https://stackoverflow.com/questions/1839422/strange-output-in-comparison-of-float-with-float-literal – n. m. could be an AI Oct 18 '17 at 04:15
  • Another option [Make C floating point literals float (rather than double)](https://stackoverflow.com/questions/32266864/make-c-floating-point-literals-float-rather-than-double) – David C. Rankin Oct 18 '17 at 04:15

2 Answers2

1

For float numbers you need to represent it as example: 0.5f .Below example is tested and working fine.

float a = 0.5;
float b = 0.7;
printf("%f",a);
printf("\n");
printf("%f",b);

if(a == 0.5f && b == 0.7f)
{
  printf("\nOK\n");
}
else
{
   printf("NOTOK\n");
}
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
User
  • 31
  • 5
0

.5 and .7 are constants and they are translated to double. Add "f" symbol at the end to tell compiler that .5f and .7f are floats.

if(a == .5f)
  printf("\nOK\n");
else
   printf("NOTOK\n");

if(b == .7f)
  printf("OK");
else
  printf("NOTOK");
Gor Asatryan
  • 904
  • 7
  • 24