编写程序自定义的递归函数long power(int m,int n),计算m的n次幂。利用此函数编程序实现:从键盘输入两个

2024-12-04 00:22:14
推荐回答(2个)
回答1:

2010-12-2 09:31的答案有错
我将其修改如下
#include "stdio.h"

long power(int m, int n)
{
long y;
if (n == 0) y = 1;
else
{
y = power(m, n / 2);
y = y * y;
if (n % 2 == 1 )
y = y * m;
}
return y;
}

int main()
{
int m, n;
scanf("%d%d", &m, &n);
long y = power(m, n);
printf("the answer is : %ld", y);
return 0;
}
另一方法
#include
long power(int m,int n)
{
long p;
if(n==0) p=1;
else p=m*power(m,(n-1));
return p;
}
void main()
{
int m,n;long k;
scanf("%d%d",&m,&n);
//if(n=0) k=1;
//else if(n<0) {printf("请重新输入\n");break;}
//else
k=power(m,n);
printf("%ld\n",k);
}

回答2:

#include "stdio.h"

long power(int m, int n)
{
long y;
if (n == 0) y = 1;
else
{
y = power(m, n / 2);
y = y * y;
if (n % 2 == 1 )
y = y * m;
}
return y;
}

int main()
{
int m, n;
scanf("%d%d", &m, &n);
long y = power(m, n);
pringf("the answer is : %ld", y);
return 0;
}