1

Somehow, when I run this program, it'll go on forever even though I wrote it in a way that makes it stop when i reaches 10. Please help.

double i;
for(i = 0; i != 10; i+= 0.1){
    printf("%.1f\n", i);
} 
HappyVirus
  • 23
  • 1
  • 6
  • 2
    Print `i` with more decimals and see what's happening. – molbdnilo Apr 24 '17 at 21:19
  • 1
    apply condition `i <=10.0` it will solve your problem... – Aafaque Abdullah Apr 24 '17 at 21:19
  • "Apply conditiion foo" without explaining why is a terrible answer. it's only a slightly better comment. – Donnie Apr 24 '17 at 21:20
  • decimal points need to be cared – some user Apr 24 '17 at 21:20
  • The point is (no pun intended) by using this http://stackoverflow.com/questions/588004/is-floating-point-math-broken I now know that technically if you push it out enough decimal places it will never actually = 10. – logixologist Apr 24 '17 at 21:21
  • [This is almost the exact same issue](https://www.securecoding.cert.org/confluence/display/c/FLP30-C.+Do+not+use+floating-point+variables+as+loop+counters). Floating point is not exact. Adding `0.1` does not guarantee all of those sums will give you exactly 10. – PaulMcKenzie Apr 24 '17 at 21:22

1 Answers1

5

0.1 cannot be represented accurately as double.

A quick fix is to change the loop condition into i < 10.

Otherwise use loop variable of an integer type, a fixed precision float, or whatever else.

Note, however, that with other decimal increments, notably the negative powers of 2 (0.5, 0.25, etc.), it might work, provided the overall iteration count is not too high.

bipll
  • 11,747
  • 1
  • 18
  • 32
  • 1
    It's useful to point out that the fraction 1/10 can't be represented in binary for the same reason that the fraction 1/3 can't be represented in decimal. 1/10 in binary repeats forever: 0.000110011001100110011.... which means that decimal 0.1 doesn't have an exact representation in the binary number system. – cdhowie Apr 24 '17 at 21:32