C语言小问题:关于全局变量和递归 :题目是用递归来求m的n次方,用尽量少的相乘的次数来解决,下面是代码

#include <stdio.h>
#include <conio.h>

int count;
int main()
{
int newpow(int m,int n);//求m的n次方
int m=0,n=0;
printf("Please input m and n:");
scanf("%d%d",&m,&n);
fflush(stdin);
printf("The reslut is :%d\nThe count is :%d",newpow(m,n),count);//为什么这里的count只会输出0???
getch();
}

int newpow(int m,int n)
{
count++;
printf("\n%d\n",count);
if(n==1)
return m;
if(n%2!=0)
return m*newpow(m,n-1);
return newpow(m,n/2)*newpow(m,n/2);
}
问题在中间注释里,请大家帮帮忙,非常感谢
我还想问一下,如何计算递归进行的次数和相乘的次数

1.int newpow(int m,int n);//求m的n次方
这个是你的注释把;
你真正的调用在printf把。
2.printf("The reslut is :%d\nThe count is :%d",newpow(m,n),count);//为什么这里的count只会输出
printf规则,先count,在newpow(m,n),所以你没调用newpow,所以count=0;
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-04
我这里是Linux环境
没有conio.h库
这个库貌似是TC自己的,而且只适用于Win平台
但仅仅看代码而言
你貌似从来没给count赋过初值
初始化的时候改成“int count = 0;”试试追问

还是不行,但是我记得全局变量是自动初始化为0的吧

追答

xxcc309说的挺有道理,你可以调整下代码结构试试

第2个回答  2011-05-04
printf根据编译器不同执行方式不同,你的编译器应该是默认从右到左执行的,先输出了count然后再输出了newpow(m,n),所以每次输出的count是系统自动赋初值的0,而不是你要的执行newpow(m,n)之后的count值;
第3个回答  2011-05-04

#include <stdio.h>

#include <conio.h>

int count = 0;

int newpow(int m,int n,int *count)

{

 ++*count;

 printf("\n%d\n",*count);

 if(n==1)

  return m;

 if(n%2!=0)

  return m*newpow(m,n-1,count);

 return newpow(m,n/2,count)*newpow(m,n/2,count);

}

int main()

{

 int newpow(int m,int n,int *count);//求m的n次方

 int m=0,n=0;

 printf("Please input m and n:");

 scanf("%d%d",&m,&n);

 printf("The count is :%d\nThe reslut is :%d\n",count,newpow(m,n,&count));//为什么这里的count只会输出0???

system("pause");

}

错在全局变量和局部变量的模糊不清。上面代码就可以解决问题。

第4个回答  2011-05-07
如果用步调就会看到结果。
相似回答