主题:
实现功能double Power(double base,int exponent),乞讨base的exponent钍。不能使用的库函数,同时也不需要考虑的大量问题。
#include<iostream>
using namespace std;
double PowerUnsigned(double base ,unsigned int exponent)
{
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
double result = PowerUnsigned(base,exponent>>1);
result *= result;
if ((exponent & 0x1) == 1)
result = result*base;
return result;
}
bool equal(double num1,double num2)
{
if ((num1 - num2 > -0.00000001) && (num1 - num2 < 0.00000001))
return true;
else
return false;
}
double Power(double base, int exponent)
{
if (equal(base, 0) && exponent < 0)
throw exception("Invaild value");
unsigned int absExponent = static_cast<unsigned int>(abs(exponent));
double result = PowerUnsigned(base, absExponent);
if (exponent < 0)
result = 1 / result;
return result;
}
int main()
{
double v1 = 2;
int v2 = -1;
cout<<Power(v1,v2);
return 0;
}