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);
}
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);
}
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.