Using pow() gives errors

JustCause picture JustCause · Sep 19, 2012 · Viewed 11.9k times · Source

Please have a look at the following code

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    //int side1 = 0;
    //int side2 = 0;
    //int rightSide = 0;

    cout << "Right Side" << setw(10) << "Side1" << setw(10) << "Side2" << endl;

    for(int i=1;i<=500;i++)
    {
        //side1++;
        //cout << side1 << endl;

        for(int a=1;a<=500;a++)
        {
            //side2++;
            //cout << "side 2 " << side2 << endl;

            for(int c=1;c<=500;c++)
            {
                //rightSide++;
                int rightSideSqr = pow(c,c);
                int side1Sqr = pow(i,i);
                int side2Sqr = pow(a,a);

                if(rightSideSqr == (side1Sqr+side2Sqr))
                {
                    cout << rightSideSqr << setw(15) << i << setw(10) << a << endl;
                 }


            }
        }
    }
}

This gives an error "PythagorialTriples.cpp:28: error: call of overloaded `pow(int&, int&)' is ambiguous". This doesn't happen if I simply used manual power like i*i, instead of the method. Can someone please explain me why this is happening? I am new to C++ anyway. Thanks

Answer

Ben Cottrell picture Ben Cottrell · Sep 19, 2012

There are multiple overloads for pow defined in <cmath>. In your code, these 3 are all equally valid, therefore the compiler is having trouble choosing the right one:

        pow(float, int);
        pow(double, int);
        pow(long double, int);

The simplest solution is to use static_cast on the first argument, to remove any ambiguity. e.g.

int side1Sqr = pow( static_cast<double>(i) ,i );
int side2Sqr = pow( static_cast<double>(a) ,a );