doubles in for loops
My professor explained that a double is not stored correctly and may cause a certain error, if we use the double many many times over as error would appear. For example
double count;
for (count=0;count<30;count+=0.1
printf("foo\n");
Because the double is added many times, this loop may run more than 300 times. If I were to need to use count as a double, how can I fix this?
Yeah, you should probably avoid using any floating point type in a loop like that. I prefer to do something like:
This way, count still increases in increments of 0.1, but the loop executes exactly 300 times regardless of any precision errors count may encompass.
Josh
vertexnormal AT linuxmail DOT org
Check out Golem: Lands of Shadow, an isometrically rendered hack-and-slash inspired equally by Nethack and Diablo.
double count=0.0;for(int c=0; c<300; c++){ count+=0.1; /* foo */}
This way, count still increases in increments of 0.1, but the loop executes exactly 300 times regardless of any precision errors count may encompass.
Josh
vertexnormal AT linuxmail DOT org
Check out Golem: Lands of Shadow, an isometrically rendered hack-and-slash inspired equally by Nethack and Diablo.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement