“avg + = abs(num)”中重载'abs(double&)'

时间:2013-07-29 11:28:37

标签: c++

以下是我遇到问题的代码。行avg += abs(num)中有错误,但我无法解决。错误代码:

error: call of overloaded 'abs(double&)' is ambigous

我意识到这是非常基本的但在书中我使用“C ++:初学者指南(第二版)” Herbert Schildt 的代码是相同的这里使用的一个例子:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    double num, avg;
    int x = 5;
    int i;

    avg = 0.0;

    for (i = 1; i <= x; ++i){

        cout << "Enter value " << i << ": ";
        cin >> num;

        avg += abs(num);

    }

    avg /= x;

    cout<< endl;
    cout << "The average is " << avg;
    return 0;
}

2 个答案:

答案 0 :(得分:4)

您没有为std::abs

的浮点重载包含正确的标头
#include <cmath>

答案 1 :(得分:3)

本书的代码是:

#include <iostream>
#include <cmath>
//        ^^^^^

using namespace std;

int main()
{
    double num, avg; // The type is double not int !!!
  //^^^^^^
    int i;

    avg = 0.0;

    for (i = 0; i < 5; ++i){
       //    ^      ^

        cout << "Enter value : ";
        //                   ^^^^
        cin >> num;

        avg += abs(num);
    }

    avg /= 5;
    //     ^

    cout<< endl;
    cout << "The average is " << avg;
    return 0;
}

我在本书的副本上找到了它......

对于std::abs,您应该包含标题cmath

#include <cmath>
  

文档:http://www.cplusplus.com/reference/cmath/abs/

编辑:abs中声明的函数cstdlib具有原型:

          int abs (          int n);
     long int abs (     long int n);
long long int abs (long long int n);

但在cmath

     double abs (double x);
      float abs (float x);
long double abs (long double x);
     double abs (T x);

但似乎在这里,您希望使用double(如果没有,您将丢失此小数部分:avg /= 5)。因此cmath版本更适合。否则,您的代码应为:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int num, avg;
  //^^^^^^
    int i;

    avg = 0;
    //    ^

    for (i = 0; i < 5; ++i){
        cout << "Enter value : ";
        cin >> num;
        avg += abs(num);
    }

    avg /= 5; // but you loose the decimal part...

    cout<< endl;
    cout << "The average is " << avg;
    return 0;
}