那丶泪 2019-04-08 11:07 采纳率: 88.9%
浏览 394
已采纳

我想用 goto码来实现这个递归 来个大佬给给思路 (还要用到进栈和出栈)

int f(int N)
{
if (N==0) return 0;
else if (N==1) return 1;
else return f(n-1)+f(n-2);
}

        例如下面这样来实现阶乘
        int fact(int n)

{
int num=1;
stack S;
L:
if(n>0)
{
S.push(n);
n=n-1;
goto L;
M:
num*=S.top();
S.pop();
}
if(!S.empty())
{
goto M;
}
return num;
}

  • 写回答

1条回答 默认 最新

  • threenewbee 2019-04-08 12:42
    关注
    // Q755200.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    
    #include <stdio.h>
    
    int stack[1000];
    int curr = 0;
    
    void push(int n)
    {
        if (curr >= 1000) printf("stack overflow!!");
        stack[curr++] = n;
    }
    
    int pop()
    {
        if (curr < 0) printf("stack empty!!!");
        return stack[--curr];
    }
    
    int f(int n1)
    {
        int a;
        int b;
    
        push(0);
        push(n1);
        push(0);
    
    callstart:
        int pos = pop();
        int n = pop();
        if (n == 1 || n == 2)
        {
            push(1);
            if (pos == 1) goto endcall1;
            if (pos == 2) goto endcall2;
            if (pos == 0) return 1;
        }
        push(n);
        push(a);
        push(b);
        push(pos);
        push(n - 1);
        push(1);
        goto callstart;
    endcall1:
        a = pop();
        pos = pop();
        b = pop();
        pop();
        n = pop();
        push(n);
        push(a);
        push(b);
        push(pos);
        push(n - 2);
        push(2);
        goto callstart;
    endcall2:
        b = pop();
        pos = pop();
        pop();
        a = pop();
        n = pop();
        push(a + b);
        if (pos == 1) goto endcall1;
        if (pos == 2) goto endcall2;
        if (pos == 0) return a + b;
    }
    
    int main()
    {
        for (int i = 0; i < 10; i++)
            printf("%d ", f(i + 1));
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog