This topic is now archived and is closed to further replies.


doubles in for loops

Recommended Posts

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?

Share this post

Link to post
Share on other sites
Yeah, you should probably avoid using any floating point type in a loop like that. I prefer to do something like:

double count=0.0;

for(int c=0; c<300; c++)
/* 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.

vertexnormal AT linuxmail DOT org

Check out Golem: Lands of Shadow, an isometrically rendered hack-and-slash inspired equally by Nethack and Diablo.

Share this post

Link to post
Share on other sites