simple yet mysterious..

Discussion in 'C++' started by ANUKANNAN, Jul 11, 2008.

  1. ANUKANNAN

    ANUKANNAN New Member

    Joined:
    Jul 11, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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..
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    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.
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice