Thread: float vs Double

  1. #1
    Registered User
    Join Date
    Jul 2006
    Posts
    3

    float vs Double

    while trying the following code
    Code:
    void main()
    {
     float a=0.7;
     if(0.7>a)
      printf("1");
    else
    printf("2");
    }
    and the output came out as 1.

    can anybody tell why??

    is it true that that it is due to double and float comparision.

  2. #2
    pwns nooblars
    Join Date
    Oct 2005
    Location
    Portland, Or
    Posts
    1,094
    Yup, best is to subtact the 2 and compare the absolute value to a range.

    EDIT:

    Why is due to how floats and doubles are stored... look into how binary decimals are calculated.

  3. #3
    Just kidding.... fnoyan's Avatar
    Join Date
    Jun 2003
    Location
    Still in the egg
    Posts
    275
    I did not try but, can a computer exactly represent 0.7 in binary? or makes its best approximation? if so, it is expexted to have a wrong result from such a comparison?

    You may want to have a look binary representation of data in computers!

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > void main()
    main returns an int - http://faq.cprogramming.com/cgi-bin/...&id=1043284376

    > if(0.7>a)
    You're comparing a double constant with a float variable.
    In the promotion of the float to a double, the value changes, and the expected comparison fails.

    Try
    if(0.7f>a)

    This is sticking plaster, not a solution.
    Wraithan's approach is much more sound.

    > is it true that that it is due to double and float comparision.
    Yes, there are many traps in floating point calculations.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copying 2-d arrays
    By Holtzy in forum C++ Programming
    Replies: 11
    Last Post: 03-14-2008, 03:44 PM
  2. Need help with program
    By HAssan in forum C Programming
    Replies: 8
    Last Post: 06-10-2007, 08:05 PM
  3. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  4. Im stuck....
    By dAzed in forum C++ Programming
    Replies: 8
    Last Post: 10-11-2004, 04:50 PM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM