can u answer Y?

Discussion in 'C' started by shanku_4ch, Jul 1, 2008.

  1. shanku_4ch

    shanku_4ch New Member

    Joined:
    Jan 7, 2007
    Messages:
    9
    Likes Received:
    0
    Trophy Points:
    0
    this program gives output as :
    C
    why?
    --------------------------------------------------------------

    i browsed and found a answer saying
    (c<0.7) 0.7 is double by default & variable c is float so the condition turns true
    then it must be true for all values but if i use

    c=0.8/*or 0.007 or 0.223*/
    if(c<0.8/*0.007 or 0.223*/)

    it prints C++


    i want answer for this!!!!
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Check to see if the value of a is 0.6999999999999
     
  3. simcopter

    simcopter New Member

    Joined:
    Jul 2, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Simulations Software Engineer
    Location:
    Phoenix, AZ
    you are running into a precision issue between floats and doubles. The easiest way to fix it is to add a 'f' to the literal telling the compiler to store it as a float. the code should work then.

    Code:
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    float a=0.7f;
    if(a<0.7f)
    printf(" C ");
    else
    printf("c++");
    getch();
    }
    
    this should work as you would expect.

    The import take away is that when comparing floats and doubles it gets muddy if the numbers are really close together because of the different number of significant bits for each type.
     
  4. shanku_4ch

    shanku_4ch New Member

    Joined:
    Jan 7, 2007
    Messages:
    9
    Likes Received:
    0
    Trophy Points:
    0
    but the same program gives other output if i use other values other then 0.7
     

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