0

I am trying to learn c programming and I came across this problem which I dont seem to understand. Here is the syntax double x;

  int flag = 0;
  for(x = 0; x <= 2.0; x+=0.1) {
      printf("%f\n",x);
      printf("%d\n", x==0.300000);
      if(x==0.3) {
         printf("yes\n");
         flag = 1;
      }
  }
  if(flag == 0) {
      printf("no\n");
  }

how come the output is no. I though when the loop reaches 0.3, the flag would be set to one and yes would be printed. How come that is not the case?

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
  • Please don't include line numbers in code snippets - it means people can't paste it into an editor and compile/run it. – Oliver Charlesworth Jun 13 '17 at 17:18
  • 1
    1/10 is periodic in binary (just like 1/3 is periodic in decimal), so it can't be stored accurately as a floating pointing point number. – ikegami Jun 13 '17 at 17:27

0 Answers0