描述
Implement pow(x, n).
#include
#include
using namespace std;
#define eps 0.0000001
bool flag = true;
double MyPow(double x, int n)
{
if (n == 0)
{
if (abs(x) >= eps)
return 1;
else
{
cerr << "0的0次方无意义!" << endl;
flag = false;
return -1;
}
}
else if (n > 0)
{
if (abs(x) < eps)
{
return 0;
}
else
{
if (n % 2 == 0)
{
double temp=MyPow(x, n / 2);
return temp*temp;
}
else
{
double temp = MyPow(x, (n-1) / 2);
return x*temp*temp;
}
}
}
else
{
if (abs(x) >= eps)
return 1.0 / MyPow(x, -n);
else
{
cerr << "0的" << n << "次方无意义!" << endl;
flag = false;
return -1;
}
}
}
int main()
{
int n = 5;
double x = 4;
double res = MyPow(x, n);
if (flag)
cout << res << endl;
}