[Tutor] Loop over floating point values

Amit Saha amitsaha.in at gmail.com
Mon Dec 2 13:57:30 CET 2013


On Mon, Dec 2, 2013 at 10:27 PM, Dave Angel <davea at davea.name> wrote:
> On Mon, 2 Dec 2013 16:28:38 +1000, Amit Saha <amitsaha.in at gmail.com> wrote:
>>
>> Indeed, that's a good point. Surprisingly, C does it just fine:
>
>
>
>> # include <stdio.h>
>
>
>
>> int main(int argc, char **argv)
>> {
>>   float x = 0.0;
>>   while(x<1)
>>     {
>>       x += 0.1;
>>       printf("%f\n", x);
>>     }
>
>
>
>>   return 0;
>> }
>
>
>
>> gives the following output:
>
>
>
>> 0.100000
>> 0.200000
>> 0.300000
>> 0.400000
>> 0.500000
>> 0.600000
>> 0.700000
>> 0.800000
>> 0.900000
>> 1.000000
>
>
> Fine???? The output is pretty,  but thoroughly wrong. There's an extra value
> at the end.

You missed the fact that I am printing the value of x *after* incrementing it.



-- 
http://echorand.me


More information about the Tutor mailing list