What is the reason for this strange floating point result

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • maiyappan
    New Member
    • Oct 2009
    • 4

    What is the reason for this strange floating point result

    float a=9.9;
    if(a<9.9) printf("true");
    else printf("false") ;
    ans:true how is it possible?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Easy, floating point numbers are an approximation, approximations can change when operated on.

    You have assigned the double constant (9.9)to a float variable so it has converted that double to float.

    Then you compare the float variable to a double constant (9.9) so the compiler converts the variable from a float to a double.

    So note that in the first 2 lines of your code the constant double 9.9 is implicitly cast down to a float and the implicitly cast back up to a double. With-in those casts it is perfectly with-in the relms of possibility that 9.9 becaomes 9.8999999999999 9 or less so true gets printed.

    To avoid it either define a as a double or use floating point constants 9.9f to avoid implicit casts.

    Try reading this too;

    Comment

    • maiyappan
      New Member
      • Oct 2009
      • 4

      #3
      thank u banfa may i know u r name

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Sorry no; as a matter of personal security policy I don't give out personal information to the general public :-7

        Comment

        Working...