vijay <Ta***********@yahoo.com> wrote:

What happens to float variable in loops. For example,
float f=8.7;

if(f<8.7)

printf("less");

else if(f==8.7)

printf("equal");

else if(f>8.7)

printf("more");
prints "less". Shouldn't it print "equal".

No, you can't expect that. The basic problem is that numbers are

stored with a finite number of digits. And numbers like 8.7 are

no simple looking numbers anymore when converted to binary but

have an infinite number of digits (like one third is an infinite

fraction when written in base 10). But since you only have a

finite numbers of bits to store them in, the numbers get truncated.

So most floating point numbers can be stored only as an approxi-

mation and what's stored of your 8.7 is probably something like

8.6999998 instead of 8.7 - you can easily see that effect when

you try to print it out with enough digits, try e.g.

printf( "%20.18f\n", f );

Moreover, since (usually) floats have less bits than doubles,

the same number stored in a float and a double variable will

differ - just try it out with

printf( "%20.18f %20.18f\n", f, 8.7 );

This also indicates that "8.7" isn't treated as a float but

as a double - all calculations in C are done per default in

double and all constants like "8.7" are treated as doubles -

to avoid that you would have to write "8.7f" instead. So what

you do in your program is comparing the value of the float

variable 'f' with the value of 8.7 when stored as a double.

But since these values typically differ you hardly ever will

get "less" printed out (except for numbers that can be stored

using a small number of digits, your result would be different

if you would use e.g. 2.5 instead of 8.7).

So the first thing to keep in mind when dealing with floating

point numbers is that comparing them for equaliy will typically

only work by accident.

Regards, Jens

--

\ Jens Thoms Toerring ___

Je***********@physik.fu-berlin.de
\__________________________

http://www.toerring.de