Changing an int datatype into float

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alenik1989
    New Member
    • Oct 2007
    • 64

    Changing an int datatype into float

    how can i chang a datatype int into float in the middle of a function that uses arrays?
    my func is

    [CODE=txt]
    int avrg(int x[],int y)
    {
    int counter;
    float average,sum=0;
    for(counter=0;c ounter<y;counte r++)
    sum+=x[counter];
    float counter;
    average=sum/counter;
    return average;
    }
    [/CODE]
    in this func i want to change the counter which is int into float after the expression
    sum+=x[counter] in order to get the average in correct decimal places!!!
    please help ASAP!!!!
  • Studlyami
    Recognized Expert Contributor
    • Sep 2007
    • 464

    #2
    you could just do:
    Code:
    avg = sum/ (float)counter; //casts counter into a float

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      And while we are chatting so pleasantly, remember that the average of 5 and 2 is 3 and is not 3.5.

      That is, there are 3 2's in 7. You can't have half a 2. Integers have no decimal portion.

      The value 2 represents all values between 2 and less than 3.

      Further, the laws of significant figures say that a result cannot be more accurate than the coarsest of its components. That is, starting out with 5 and 2 you cannot have 3.5 as an average unless you start with 5.0 and 3.0.

      Remove the cast.

      Integer aritmetic always yields integer results.

      Do not mix integer and floating point. Floating point is for scientific work where extreme accuracy is not required. Integers are meant for everything else.

      Comment

      • Alenik1989
        New Member
        • Oct 2007
        • 64

        #4
        Originally posted by weaknessforcats
        And while we are chatting so pleasantly, remember that the average of 5 and 2 is 3 and is not 3.5.

        That is, there are 3 2's in 7. You can't have half a 2. Integers have no decimal portion.

        The value 2 represents all values between 2 and less than 3.

        Further, the laws of significant figures say that a result cannot be more accurate than the coarsest of its components. That is, starting out with 5 and 2 you cannot have 3.5 as an average unless you start with 5.0 and 3.0.

        Remove the cast.

        Integer aritmetic always yields integer results.

        Do not mix integer and floating point. Floating point is for scientific work where extreme accuracy is not required. Integers are meant for everything else.
        what are u saying?
        i got it
        i just changed the function type from int to float that was the problem!!!!!
        and i got 3.5 not 3

        Comment

        Working...