#include <stdio.h>
#include <stdlib.h>
int show(int number,int count);
int main()
{
int count;
int number;
while(scanf("%d%d",&number,&count)==2){
if(number==0){
printf("the answer is 0");
}
else{
if(count==0){
printf("the answer is 1");
}
if(count>0){
printf("the answer is %d\n",show(number,count));
}
}
printf("please try again:");
}
return 0;
}
int show(int number,int count){
if(count>0)
return show(number,(count-1))*number;
}
它的运行结果不对,查了好久看不出来为什么。
更奇怪的是把上述所有类型换成double以后,乱码了
全选复制放进笔记#include <stdio.h>
#include <stdlib.h>
double show(double number,double count);
int main()
{
double count;
double number;
while(scanf("%lf%lf",&number,&count)==2){
if(number==0){
printf("the answer is 0");
}
else{
if(count==0){
printf("the answer is 1");
}
if(count>0){
printf("the answer is %f\n",show(number,count));
}
}
printf("please try again:");
}
return 0;
}
double show(double number,double count){
if(count>0)
return show(number,(count-1))*number;
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
你的递归函数里没有结束递归的条件啊?count>0的时候会不断往你的最终结果里面添加乘数因子,那么到count=0了之后呢?不是应该指定返回一个1吗?这样才能结束递归调用。
int show(int number,int count){
if(count>0)
return show(number,(count-1))*number;
else if(count==0)
return 1;
}
这样一来,main函数里面单独给count=0的情况写一个if分支也是不需要的,因为它只能判断初始输入值,无法判断递归执行过程中,count递减到哪个值了——还不如凡是count>=0正确就统一留到show()函数里面来判断。
全选复制放进笔记int main()
{
int count;
int number;
while(scanf("%d%d",&number,&count)==2){
if(number==0){
printf("the answer is 0");
}
else{
if(count>=0){
printf("the answer is %d\n",show(number,count));
}
}
printf("please try again:");
}
return 0;
}