关于 C 语言 For 循环的问题请教

2018-11-22 20:12:49 +08:00
 FalconWang
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int level(int l)
{
int sum;
if(l==1)
sum=1;
else
sum=level(l-1)*2;
return(sum);
}

int main()
{
int level(int l);
char ch;
int a,b=1;
printf("Study is a long and hard road.\n");
printf("The more you study,the further you will reach.\n");
printf("Such as if you learn 1 year, you will reached level %d.\n",level(1));
do
{
b=b+1;
printf("such as if you learn %d years, you will reached %d level.\n",b,level(b));
printf("do you want to continue?(y/n).\n");
ch=getchar();
getchar();
}while(ch=='y'||ch=='Y');
}

期望结果为:
学习 1 年,到达第 1 级
学习 2 年,到达第 2 级
以此类推...

上面这段程序结果:到达的级别数呈指数增长,想知道原因,拜托各位了,感激不尽...
2277 次点击
所在节点    C
4 条回复
weifengzi2009
2018-11-22 20:21:38 +08:00
你这个 level 函数递归每次都乘以 2,那不是 2*2*2*2*2 这样子么?
GTim
2018-11-22 20:29:36 +08:00
```
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int level(int l)
{
return l == 1 ? 1 : level(l-1)+1;
}

int main()
{
char ch;
int a,b=1;

printf("Study is a long and hard road.\n");
printf("The more you study,the further you will reach.\n");
printf("Such as if you learn 1 year, you will reached level %d.\n",level(1));

do {
b=b+1;
printf("such as if you learn %d years, you will reached %d level.\n",
b,level(b));
printf("do you want to continue?(y/n).\n");

ch=getchar();
getchar();

} while(ch == 'y'|| ch== 'Y');
}
```

测试格式化代码

以上是楼主代码的简化和想要的版本
FalconWang
2018-11-22 20:32:36 +08:00
感谢各位解答 问题已解决
wutiantong
2018-11-23 11:45:19 +08:00
@GTim 只有主题正文支持 markdown,回复内容不支持。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/510523

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX