北漂程序员-阿力 2016-04-02 16:24 采纳率: 100%
浏览 2760
已采纳

c语言循环里的递归问题

求大神们,帮我分析一下这个程序怎么运行的

#include
void test(int n)
{
int x=0,i=0;
if(n==1){
printf("n:%d x:%d i:%d\n",n,x,i);
return ;
}else{
printf("n:%d x:%d i:%d\n",n,x,i);

    for(i=0;i<3;i++){
        test(n-1);
        x=1;
    }
}

}

int main()
{
test(3);
return 0;
}

运行结果如图:
图片说明

  • 写回答

4条回答 默认 最新

  • threenewbee 2016-04-02 21:07
    关注

    你的程序可以改写成不用递归,使用堆栈的形式:

     #include<stack>
    #include<stdio.h>
    using namespace std;
    
    void test(int n)
    {
        stack<int> st;
    funcstart:
        int x=0,i=0;
        if(n==1){
            printf("n:%d  x:%d   i:%d\n",n,x,i);
            goto brkpos;
        }else{
            printf("n:%d  x:%d   i:%d\n",n,x,i);
    
            for(i=0;i<3;i++){
                st.push(x);
                st.push(i);
                st.push(n);
                n=n-1;
                goto funcstart;
    brkpos:
                if (st.empty()) return;
                n=st.top();
                st.pop();
                i=st.top();
                st.pop();
                x=st.top();
                st.pop();
                x=1;
            }
        }
        goto brkpos;
    }
    
    int main()
    {
        test(3);
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题