How not to write a loop

Richard A. O'Keefe ok at quintus.UUCP
Tue Mar 1 09:02:43 AEST 1988


In article <832 at unmvax.unm.edu>, mike at turing.UNM.EDU (Michael I. Bushnell) writes:
> I see NOTHING which precludes:
> 	float x;
> 	for (x = 0; x < 20; x += .5) printf("%f\n", x);
> The output would, of course, be
> 	0.0
> 	0.5
> 	...
> 	19.5

Quite right, there is nothing in K&R (or dpANS) to prohibit this.
But you have provided a good illustration of why people disparage
the use of floating-point variables in loop control.
THERE IS NO "OF COURSE" ABOUT THAT OUTPUT!

You should not be surprised to see as the last value
	19.99999
I just tried the very similar loop
	for (x = 0; x < 21; x += .3)	/* .3 divides 21 exactly */
By analogy with your "of course", the last output should obviously
be 20.7.  In fact, when I tried it just now, the last output was
	20.999994



More information about the Comp.lang.c mailing list