What's wrong with this code?

Discussion in 'OT Technology' started by nucklearknight, Jan 11, 2009.

  1. nucklearknight

    nucklearknight New Member

    Joined:
    Sep 21, 2008
    Messages:
    367
    Likes Received:
    0
    Location:
    San Francisco, California
    I wrote this C++ code

    Code:
    /*
        This program displays the absolute value
        of the average of 5 numbers imputed by
        the user
    */
    
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    int main() {
    
        int i;
        double val, avg;
    
        avg = 0.0;
    
        for(i = 0; i < 5; i++) {
            cout << "Enter a value: ";
            cin >> val;
    
            avg = avg + abs(val);
        }
        avg = avg / 5;
    
        cout << "The average of the absolute value of the five numbers is " << avg;
    
        return 0;
    }
    
    and when I compile it I get this error:
     
  2. CodeX

    CodeX Guest

    The abs function is for integers, use fabs() instead. Means floating absolute value.
     
    Last edited by a moderator: Jan 11, 2009
  3. nucklearknight

    nucklearknight New Member

    Joined:
    Sep 21, 2008
    Messages:
    367
    Likes Received:
    0
    Location:
    San Francisco, California
    I try that and I get this:

     
  4. CodeX

    CodeX Guest

    unused variable?

    its a function... the compiler should not think its a variable if you are using it correctly.

    You needed to replace the line:
    avg = avg + abs(val);

    With the line:
    avg = avg + fabs(val);

    Or, more succinctly:
    avg += fabs(val);

    Is that what you did?
     
  5. White Stormy

    White Stormy Take that, subspace!

    Joined:
    Sep 17, 2002
    Messages:
    85,489
    Likes Received:
    70
    Location:
    Sparkopolis
    you probably need #include <cmath> to use abs() or fabs()
     
  6. CodeX

    CodeX Guest

    yes you are right, I missed that.

    however abs() and labs() are in cstdlib, fabs() and all other derivatives are in math.h
     
  7. nucklearknight

    nucklearknight New Member

    Joined:
    Sep 21, 2008
    Messages:
    367
    Likes Received:
    0
    Location:
    San Francisco, California
    I added <cmath> and it worked. Thanks!
    XD
     

Share This Page