- 1

for (doublCe y = .1; y != 1.0; y += .1) { printf("%f\n", y); }

Correct the error and rewrite the correct answer

5th Dec 2021, 8:47 AM
Christine Jane Dulay
Christine Jane Dulay - avatar
1 Antwort
+ 2
Syntax error: doublCe should be double. Potential floating point accumulated error: y += .1 may skip past the end condition, y != 1.0, and loop forever. Understand that some decimals, such as 0.1, are imprecise in binary due to limited number of bits, just like 1/3 is imprecise in decimal as 0.33333(3...) with limited digits. If you add up 0.33333 three times you get only 0.99999 instead of 1.0. To fix the code, change loop condition from y != 1.0; to y < 1.0;. A superior fix that gives better precision requires rewriting the loop using a whole number increment. Consider: for (double y = 1.0; y < 10.0; y += 1.0) { printf("%f\n", y*0.1); } To potentially improve precision further, replace y*0.1 with whole number division, y/10.0.
5th Dec 2021, 9:42 AM
Brian
Brian - avatar