Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   simple yet mysterious.. (http://www.go4expert.com/forums/simple-yet-mysterious-t12040/)

ANUKANNAN 11Jul2008 21:21

simple yet mysterious..
 
hai everyone..
here is a small code that produced interseting outputs:
guess u all know how this is..ok let me not beat abt the bush..
main()
{
float i=1.1;
double j=1.1;
if(i==j)
cout<<"hai";
else
cout<<"bye";
}if u give i=1.0 or 1.5 the output is hai
else it's bye y is that so?if u know the reason then am lucky..

shabbir 12Jul2008 11:18

Re: simple yet mysterious..
 
First thing first. Try having the thread in the right forum for better response.

Now about your query the comparison is done based on float and double and so check with the same data type and see what happens or else have a type cast.

xpi0t0s 15Jul2008 13:50

Re: simple yet mysterious..
 
The explanation is not an easy one to give but you may be able to work it out.

1.0 and 1.5 work fine. What about 1.25, 1.125, 1.0625, 1.03125? You may be able to think of others in this sequence.
What are the above numbers in binary? E.g. 1.0_10=1.0_2. 1.5_10=1.1_2. 1.25_10=1.01_2 (_10 and _2 mean "base 10" and "base 2").
What are the binary representations of the numbers where the equality test fails, (a) in float precision; (b) in double precision?
What if i and j could store decimal numbers exactly, and, say, i=1.333 and j=1.333333. Should the test i==j return TRUE or FALSE?

By working through the above you'll learn a heck of a lot more than if I just gave you the answer directly.


All times are GMT +5.5. The time now is 18:07.