请任何人向我解释此递归代码?

时间:2018-11-14 05:02:41

标签: c

#include <stdio.h>
int fun(int,int *);
int main()
{
 int x = 5; // variable x and its value is 5
printf("%d,the value of fun is:",fun(5,&x));
return 0;
}
int fun(int n,int *fp)
{
  int t,f;

  if(n <=1)
   {
    *fp = 1;
    return 1;
   }
  t = fun(n-1,fp);
  f = t + *fp;
  *fp = t;
  return (f);
 }

我有一个测试,要求输出此代码。 输出为8,但我无法理解此代码的逻辑。

2 个答案:

答案 0 :(得分:0)

您需要逐行浏览功能。 -为了清楚起见,我省略了If条件,直到最后一步。

O(n)

最终打印值为// Function Call iteration n = 5, fp = 5 int fun(int n,int *fp) { t = fun(n-1,fp); -- Call with n = 4, fp = 5.. The recursive function is called here and the return value needs to be checked only after all the functions return. // First Call t = fun(n-1,fp); -- Call with n = 3, fp = 5 // Second call t = fun(n-1,fp); -- Call with n = 2, fp = 5 // Third call t = fun(n-1,fp); -- Call with n = 1, fp = 5 // Fourth call -- Here the If condition is valid, and the recursive function ends. We can now check the return values of all functions in reverse order. if(n <=1) { *fp = 1; return 1; } // After Third call -- fp = 1, t=return of previous == 1 f = t + *fp; *fp = t; -- fp = 2 return (f); -- return 2 // After Second call f = t + *fp; -- f = 4 *fp = t; -- fp = 4 return (f); -- return 4 // After First call -- t = 4, fp = 4 f = t + *fp; -- f = 8 *fp = t; -- fp = 8 return (f); -- return 8

答案 1 :(得分:0)

#include <stdio.h>
    int fun(int,int *); // <- define function
    int main()
    {
     int x = 5; // variable x and its value is 5
    printf("%d,the value of fun is:",fun(5,&x)); //<- print value and function call with var x pointer edit
    return 0;
    }
    int fun(int n,int *fp)//<- define function
    {
      int t,f;//two var

      if(n <=1)//if n is small end function and return value 
       {
        *fp = 1;
        return 1;
       }
      t = fun(n-1,fp); // t any val 1 en recursive method start
      f = t + *fp;
      *fp = t;
      return (f);
     }

    one

    n = 5     x = 5

    part 1
    n=5 <= 1 ? -> false
    n-1 = 4    fp = x = 5
    call function fun(4,5)
    -------------
    Part 2
    n=4 <= 1 ? -> false
    n-1 = 3    fp = x = 5
    call function fun(3,5)
    --------------
    Part 3
    n=3 <= 1 ? -> false
    n-1 = 2    fp = x = 5
    call function fun(2,5)
    ---------------
    Part 4
    n=2 <= 1 ? -> false
    n-2 = 2    fp = x = 5
    call function fun(1,5)
    ---------------
    Part 5
    n=1 <= 1 ? -> true
    fp = x = 1
    return 1
    --------------
    ##############
    --------------
    return Part 4
    t = 1 
    f = t=1 + fp=x=1 = 2
    fp =x=t=1
    return (f=2);
    ---------------
    return Part 3
    t = f=2 
    f = t=2 + fp=x=1 = 3
    fp =x=t=2
    return (f=3);
    ---------------
    return Part 2
    t = f=2 
    f = t=2 + fp=x=2 = 4
    fp =x=t=2
    return (f=4);
    ---------------
    return Part 1
    t = f=4 
    f = t=3 + fp=x=4 = 8
    fp =x=t=4
    return (f=8);
    ---------------

    Exit:

    8,the value of fun i

s:

好(y)