模拟求幂运算,考虑的已经很周全了

enum{Valid,Invalid};
int g_valid;
double Power(double base,int exponent)
{
	g_valid=Invalid;
	if(abs(base)<0.000001&&exponent<0)
	{
		return 0.0;
	}
	cout<<base<<"	"<<exponent<<endl;
	long double ret=1.0,b=base;
	int n=exponent;
	int sign;
	if(n>=0)
		sign=1;
	else
	{
		sign=-1;
		n=-n;
	}
	while(n>0)
	{
		if(n%2==0)
		{
			b=b*b;
			n=n>>1;
		}
		else
		{
			ret=ret*b;
			n=n-1;
		}
	}
	g_valid=Valid;
	if(sign>0)
	{
		return ret;
	}
	else
	{
		return 1/ret;
	}
}

  

posted on 2013-07-23 17:11  dyc0113  阅读(202)  评论(0编辑  收藏  举报

导航