Simple atof() question

Chris Torek torek at elf.ee.lbl.gov
Wed Mar 20 05:32:11 AEST 1991


>In <1214 at caslon.cs.arizona.edu>, armstron at cs.arizona.edu writes:
>>When I run this simple program I get n = 37.549999 instead of
>>n = 37.55.  What am I doing wrong?

Welcome to the Wacky World of Floating Foint, I mean Point!

In article <1991Mar19.181719.7821 at cs.widener.edu> brendan at cs.widener.edu
(Brendan Kehoe) writes:
>  I have a feeling it's got something to do with the way printf takes
>  its argument .. notice if ya do
>	printf("n = %.2f\n", n);
>  you do get 37.55.

The problem is that the number 37.55 does not exist.  There are two
numbers that are pretty close to 37.55, both of which are `about'
1.1734375 x 32 (the number you want), but one is just a bit under,
and the other just a bit over.  Your runtime system picks the lower
value, and when you print it out it says `37.549999'.

Using %.2f tells printf to `round to two digits after the decimal point'.
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427)
Berkeley, CA		Domain:	torek at ee.lbl.gov



More information about the Comp.lang.c mailing list