C and casting - why does this program stop at 6?

I edited the C program for my purpose, there was no machine translation before, and the iteration stopped at i = 1, now with the type that it stops at i = 6.

Any ideas why? Thanks in advance!

int main(void) { int i = 0; double d = 0.0; while ( (i == (int) (d * 10)) && (i < 10) ) { i = i + 1; d = (double) (d + 0.1); printf("%d %lf\n", i, d); } printf("%d %lf\n", i, d); getch(); return 0; } 
+4
source share
3 answers

As has been said many times, the reason this does not work is that binary floating point numbers cannot represent binary numbers with decimal point, this is simply not possible. To learn more, check out this great article:

What Every Programmer Should Know About Floating-Point Arithmetic

Now, on the more practical side of things, when using a floating point and comparing it to a different number, you should almost always have a round value or use the epsilon value, for example:

 if (ABS(doubleValue - intValue) < 0.00001) // 0.00001 is a margin-of-error for floating point arithmetic // the two numbers are even (or close to it) 
+1
source

Floating-point arithmetic is inaccurate. A value of 0.1 not exactly representable in binary floating point. Recommended reading here: What every computer scientist needs to know about floating point arithmetic .

At some point in the program, d gets a little less than i/10 due to a rounding error, and so your loop ends.

+4
source

In addition to other answers, I would like to answer the question why the cycle ends earlier with the condition i == (d * 10) than with i == (int) (d * 10) .

In the first case, the value of int on the left side == increases to double, so the inequality occurs when the accumulated error in d*10 is either positive or negative (for example, 0.999999 or 1.000001).

In the second case, the right-hand side is truncated to int, so inequality occurs only when the error is negative (for example, 5.999999). Therefore, the first version will fail.

+2
source

Source: https://habr.com/ru/post/1432729/


All Articles