What is problem in type declaration FLOAT?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sauravamatyaw
    New Member
    • Oct 2013
    • 5

    What is problem in type declaration FLOAT?

    Code:
    #include <stdio.h>
    #include <conio.h>
    void main ()
    {
    float a;
    clrscr();
    a=11/5;
    printf ("%f",a);
    getch ();
    }
    Output: 2.000000
    Since "a" is defined as float it should have given "2.2" output but gives an integer value.
    WHATS WRONG?
    Last edited by Rabbit; Oct 21 '13, 06:35 AM. Reason: Please use [CODE] and [/CODE] tags when posting code or formatted data.
  • JATINCSE
    New Member
    • Sep 2013
    • 4

    #2
    use the value a is either in any format given 11.0/5.0 or 11.0/5 or 11/5.o so you will get the correct answer

    Comment

    • sauravamatyaw
      New Member
      • Oct 2013
      • 5

      #3
      @JATINCSE cant i do it without putting ".0" behind ? is it compulsory?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        You a mixing integer and floating point division:

        Code:
        a = 11/5;
        11/5 is 2. Integers have no decimal portion.

        Considering the variable is a float you would code:

        Code:
        a = 11.0f/5.0f;
        If you code:
        Code:
        a = 11.0/5.0;
        you will get a warning from the compiler. The 11.0/5.0 is a double and then you assign the double to a float, which is smaller, so you get a warning about possible data loss.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          @sauravamatyaw:
          The compiler first evaluates the expression on the right side of the equals sign and then assigns the computed value to the variable on the left side of the equals sign. The compiler doesn't notice the type of the left-side variable until the assignment stage; but by then it is too late -- the expression has already been evaluated using integer math.

          Comment

          • JATINCSE
            New Member
            • Sep 2013
            • 4

            #6
            @sauravamatyaw:
            i think so because it is depend upon the working of the compliler
            first it evaluates the expression on right side as on right it is the ratio of two integers so compiler will evaluate in terms of int then assign its value to float

            Comment

            Working...