一、虽然计算能够显示正确结果,但是对无效输入(即基数为0且指数为负)不能够很好的标明出来,即可能会忽略isInvaildInput的一个表达
#include<iostream>
class c_Pow
{
bool isInvalidInput;
double result;
int unsignedExponent;
public:
double g_Pow(double base, int exponent);
private:
double _g_Pow(double base, int exponent);
};
double c_Pow::g_Pow(double base, int exponent)
{
isInvalidInput = false;
if (base == 0 && exponent < 0)
{
isInvalidInput = true;
return 0.0;
}
if (exponent < 0)
{
unsignedExponent = abs(exponent);
result = _g_Pow(base, unsignedExponent);
result = 1.0 / result;
}
else
{
result = _g_Pow(base, exponent);
}
return result;
}
double c_Pow::_g_Pow(double base, int exponent)
{
double _result = 1;
for (int i = 1;i <= exponent;++i)
_result *= base;
return _result;
}
int main(int argc, char* argv[])
{
c_Pow C;
std::cout << C.g_Pow(-2, 9) << std::endl;
std::cout << C.g_Pow(0, -9) << std::endl;
std::cin.get();
return 0;
}
二、计算效率的提升,即当求某个基数的64次方时,如果使用循环进行计算,则需要进行64次迭代
换一种想法,即(n ^2) ^2··· ^2来进行计算,即可减少一部分的运算,则64次方就只需要做6次乘方运算即可,具体代码如下:
#include<iostream>
class c_Pow
{
bool isInvalidInpput;
double result;
int unsignedExponent;
public:
double g_Pow(double base, int exponent);
private:
double _g_Pow(double base, int exponent);
};
double c_Pow::g_Pow(double base, int exponent)
{
isInvalidInpput = false;
if (base == 0 && exponent < 0)
{
isInvalidInpput = true;
return 0.0;
}
if (exponent < 0)
{
unsignedExponent = abs(exponent);
result = _g_Pow(base, unsignedExponent);
result = 1.0 / result;
}
else
{
result = _g_Pow(base, exponent);
}
return result;
}
double c_Pow::_g_Pow(double base, int exponent)
{
if (exponent == 0)return 1;
if (exponent == 1)return base;
double _result = _g_Pow(base, exponent >> 1);//使用位运算比除法更加高效率
_result *= _result;
if ((exponent & 0x1) == 1)//使用位运算效率更高
_result *= base;
return _result;
}
int main(int argc, char* argv[])
{
c_Pow C;
std::cout << C.g_Pow(-2, 9) << std::endl;
std::cout << C.g_Pow(0, -9) << std::endl;
std::cin.get();
return 0;
}