0

Given below is a segment of code in C

float k=0.6;

if(k==0.6)
  printf("yes they are equal");
else
  printf("no they are not equal");

The above code gives output "no they are not equal". I am working on Ubuntu 12.04 gcc 4.4

I was surprised and debugged the program. The answer is no because the value of K is not equal to 0.6. I single stepped the program in gdb and i found value of k as 0.600000024. Now my question is why 0.600000024 is assigned to k and why not 0.6. when I assign 0.7 the k has a value 0.69999998. Why does this happen?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user146297
  • 79
  • 8
  • The answer is no because the value of K is not equal to 0.6. I single stepped the program in gdb and i found value of k as 0.600000024 – user146297 Apr 08 '15 at 06:05
  • The type of `0.6` is not `float`, it's `double`. There's a duplicate somewhere. – Yu Hao Apr 08 '15 at 14:01

1 Answers1

0

Correct. If you are working with float values in C you have to work with a set difference.

You can use

DBL_EPSILON of the Header float.h
if ((k - 0.6) < DBL_EPSILON){ ... }
Andréw
  • 96
  • 1
  • 11