double power_negative(double n,int p)
蚌埠網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)建站!從網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、APP開發(fā)、響應式網(wǎng)站建設等網(wǎng)站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)建站于2013年創(chuàng)立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設就選創(chuàng)新互聯(lián)建站。
{
double pow = 1;
int q;
q=-p;
if(q0)
pow = power_negative(n,1-q) / n;
return pow;
}
改成這樣,雖然你那個寫的是遞歸調(diào)用,但是返回的卻是1/pow,那么就會是0.5 * 2 * 0.5 * 2 * 0.5這樣的形式返回,所以最終無論是多少,結(jié)果都是0.5,而且遞歸時應該用1-q,因為你調(diào)用負數(shù)求冪,必須使參數(shù)為負才會正確
long
double
_pow_i(
long
double
_X,
int
_Y
)
{
if
(
!_Y
)
return
1;
//
次冪為0的情況
if
(
!(_Y-1)
)
return
_X;
//
當_Y
=
1的情況則返回結(jié)果_X
return
_X
*
_pow_i(
_X,
abs(_Y)-1
);
//
每一步返回
_X
*
上一次的乘積,_Y
減1計數(shù)
}
long
double
_pow(
long
double
_X,
int
_Y
)
{
long
double
_Z
=
_pow_i(
_X,
_Y
);
return
_Y
?
1
/
_Z
:
_Z;
}
因為寫在一起的話不好解釋,所以分開正負的情況,_pow就是判斷次冪是否為負數(shù),是負數(shù)就等于1/那個數(shù)個正次冪。
#includestdio.h
double power(double x,int n)
{if(n==0)return 1.0;
else if(n0)return x*power(x,n-1);
else return power(x,n+1)/x;
}
int main()
{double x;
int n;
scanf("%lf%d",x,n);
printf("%lf\n",power(x,n));
return 0;
}
#includestdio.h
double power_positive(double n,int p);
double power_negative(double n,int p);
int main(void)
{
double x,xpow;
int exp;
printf("Enter a number and the integer power to which\n");
printf("the number will be raised.Enter q to quit.\n");
while (scanf("%lf %d",x,exp)==2)
{
if (x==0)
printf("%lf to the power of %d is 0.\n",x,exp);
else
{
if (exp==0)
printf("%lf to the power of %d is 1.\n",x,exp);
else if (exp0)
{
xpow=power_positive(x,exp);
printf("%lf to the power of %d is %lf.\n",x,exp,xpow);
}
else
{
xpow=power_negative(x,exp);
printf("%lf to the power of %d is %lf.\n",x,exp,xpow);
}
}
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip --BYE!\n");
return 0;
}
double power_positive(double n,int p)
{
double pow=1;
if (p0)
pow=n*power_positive(n,(p-1));
return pow;
}
double power_negative(double n,int p) //用遞歸實現(xiàn)
{
if (p==-1)return 1/n;
else
return (1/n)*power_negative(n,p+1);
}