FalconWang
V2EX  ›  C

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

  •  
  •   FalconWang · Nov 22, 2018 · 3112 views
    This topic created in 2730 days ago, the information mentioned may be changed or developed.
    #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 级
    以此类推...

    上面这段程序结果:到达的级别数呈指数增长,想知道原因,拜托各位了,感激不尽...
    4 replies    2018-11-23 11:45:19 +08:00
    weifengzi2009
        1
    weifengzi2009  
       Nov 22, 2018
    你这个 level 函数递归每次都乘以 2,那不是 2*2*2*2*2 这样子么?
    yemoluo
        2
    yemoluo  
       Nov 22, 2018   ❤️ 1
    ```
    #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
        3
    FalconWang  
    OP
       Nov 22, 2018
    感谢各位解答 问题已解决
    wutiantong
        4
    wutiantong  
       Nov 23, 2018
    @GTim 只有主题正文支持 markdown,回复内容不支持。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4312 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 55ms · UTC 05:21 · PVG 13:21 · LAX 22:21 · JFK 01:21
    ♥ Do have faith in what you're doing.