您的位置:首页 > 其它

数值的整数次方

2016-02-14 23:33 225 查看
计算的时候,如果指数是负数,则先计算他的正数,然后求结果,再最后求这个结果的倒数,就是最终答案

考虑一个特殊情况,那就是如果底数是0,指数是负数,这样按照上面办法的话,最后一步,分母会变成0,这样是非法的

代码如下
#include <iostream>
using namespace std;
bool  gInvalid=false;
double PowWithUnsignedExponent(double base,unsigned int exponent)
{
double result=1.0;
for(int i=1;i<=exponent;i++)
{
result*=base;
}
return result;

}
bool equal(double a,double b)
{

if((a-b)>-0.00001&&(a-b)<0.00001)
return true;
return false;
}
double Pow(double base,double exponent)

{
gInvalid=false;
//如果底数是0   指数是负数  那就应该返回错误

if(equal(base,0.0)&&exponent<0)
{
gInvalid=true;
cout<<"the base and exponet are less than 0,illegle parameter!";
exit(1);
}
unsigned int absExponent=(unsigned int)exponent;
if(exponent<0)
absExponent=(unsigned int)(-exponent);
double ret=PowWithUnsignedExponent(base,absExponent);
if(exponent<0)
ret=1.0/ret;
return ret;

}

int main()
{

cout<<Pow(0,-2)<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: