what is the reason of giving output is ravi except rahul

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • indiver
    New Member
    • Aug 2010
    • 2

    what is the reason of giving output is ravi except rahul

    Code:
    #include<stdio.h>
    #include<conio.h>
    main()
    {
    float p=0.7;
    if(p==0.7)
    printf("rahul");
    else
    printf("ravi");
    output: ravi

    why????
    Last edited by Nepomuk; Sep 2 '10, 10:21 PM. Reason: Please use CODE tags.
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    0.7 seems to be a popular number - http://bytes.com/topic/c/answers/894...tation-numbers

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You cannot use the == operator with floating point.

      Due to rounding, numbers that are close in value may test equal.

      Ditto for !=.

      Comment

      • haicp
        New Member
        • Sep 2010
        • 4

        #4
        In this kind of comaprisions, 99% of the time the else part of the if condition gets executed.

        In this example, when you try to compare 0.7 with 0.7, what actually happens internally is, one of the 0.7 is interpreted as 0.6999999999.

        Floating point representation is machine dependent.

        Even though there is not much of a difference between 0.7 and 0.6999999999, the if condition fails.

        So, never use floating numbers for comparision.

        Comment

        Working...