Subject: Unexpected "double" behaviour
To: None <netbsd-help@netbsd.org>
From: Matthew Fincham <matthewf@cat.co.za>
List: netbsd-help
Date: 09/26/2001 09:22:09
Hello

I am seeing some unexpected behaviour when casting a double to an int, and
was wondering if there is an explanation for it. The following program shows
the problem:

1> int main()
2> {
3> double d;
4> int i;
5>
6> d=(double)4.52;
7> d=d*100;
8> i=(int)d;
9>
10> printf("d=%f, i=%d\n\r",d,i);
11> return 0;
12> }

While I would expect the resulting printout to be "d=452.00000, i=452", what
I get is "d=452.00000, i=451". There are a couple of strange things about
this:

* It is only with the value of 4.52 that this occurs. All other values are
correctly converted.
* When I try a float instead of a double, the result is correct.
* If in line 6 I use "d=(float)4.52" the resulting printout is "d=451.99998,
i=451". This make me think that the accuracy is lost in the conversion from
a float to a double.

I would appreciate any ideas on why this is like this. I can get around the
problem by using a float, but there is either a gap in my understanding, or
a some other problem that would be nice to know about :-) .

Thank you

Matthew Fincham