c语言中递归法求幂函数 c语言递归函数的例题

C语言题.用递归法写一个求幂的函数,并在主函数实现调用.要用c语言,不要c++的 。提示/*x^n的值必须小于32767,否则输出的就是负数 。因为,int只有这么大,正常的pow函数应该是float型或是double型 , 参数也应是float或是double型 。*/
#include stdio.h
int power(int x,int n)
{
if (n1)
{
return x*power(x,n-1);
}
else
{
if (n0)
return x;
else
return 1;
}
}
void main()
{
int x,n;
printf("input x,n:");
scanf("%d%d",x,n);
printf("%d",power(x,n));
getch();
clrscr();
}
C语言 用递归方法求X的n次方#includestdio.h
int power(int x,int n)
{
if(n==0)
return 1;
elseif(n%2==1)
return x*power(x,n-1);
else{
int y=power(x,n/2);
return y*y;
}
}
int main()
{
int a,b,c;
printf("enter x and n:");
setvbuf(stdout,NULL,_IONBF,0);
scanf("%d%d",a,b);
c=power(a,b);
printf("结果为%d",c);
return 0;
}
扩展资料
#includestdio.h
double power(double x,int n);
main()
{
double x;
int n;
printf("Input x,n:");
scanf("%lf,%d",x,n);
printf("%.2lf",power(x,n));
}
double power(double x,int n)
{
double a=1.0;
int i;
for(i=1;i=n;i++)
a*=x;
return a;
}
参考资料:百度百科 - 递归调用
C语言 用递归函数求数值的整数次幂 double power(double x,int p).在求数值的负数次幂时出现问题 。#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) //用递归实现
{
if (p==-1)return 1/n;
【c语言中递归法求幂函数 c语言递归函数的例题】else
return (1/n)*power_negative(n,p+1);
}
C语言 用递归函数求数值的整数次幂 double power(double x,int p)输入负整数次幂时出现问题double power_negative(double n,int p)
{
double pow = 1;
int q;
q=-p;
if(q0)
pow = power_negative(n,1-q) / n;
return pow;
}
改成这样,虽然你那个写的是递归调用,但是返回的却是1/pow,那么就会是0.5 * 2 * 0.5 * 2 * 0.5这样的形式返回 , 所以最终无论是多少,结果都是0.5,而且递归时应该用1-q,因为你调用负数求幂,必须使参数为负才会正确
c语言中递归法求幂函数的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于c语言递归函数的例题、c语言中递归法求幂函数的信息别忘了在本站进行查找喔 。

    推荐阅读