📜  C 程序的输出 | 11套

📅  最后修改于: 2022-05-13 01:56:11.186000             🧑  作者: Mango

C 程序的输出 | 11套

Shobhit 提问

#include
int fun(int n, int *fg)
{
   int t, f;
   if(n <= 1)
   {
     *fg = 1;
      return 1;
   }
   t = fun(n-1, fg);
   f = t + *fg;
   *fg = t;
   return f;
}
int main( )
{
  int x = 15;
  printf ( "%d\n", fun (5, &x));
  getchar();
  return 0;
}

在上面的程序中,会递归调用直到n小于或等于1。

fun(5, &x) 
       \
         \
       fun(4, fg)
           \
             \
            fun(3, fg)
                 \
                   \
                   fun(2, fg)
                      \
                        \
                          fun(1, fg)

fun(1, fg) 不再进一步调用 fun() 因为 n 现在是 1,并且它进入 if 部分。它将地址 fg 处的值更改为 1,并返回 1。

里面的乐趣(2, fg)

t = fun(n-1, fg); --> t = 1
  /* After fun(1, fg) is called, fun(2, fg) does following */
   f = t + *fg;      -->  f = 1 + 1 (changed by fun(1, fg)) = 2
   *fg = t;           --> *fg = 1
  return f (or return 2)

里面的乐趣(3, fg)



t = fun(2, fg); --> t = 2
  /* After fun(2, fg) is called, fun(3, fg) does following */
   f = t + *fg;       -->  f = 2 + 1 = 3
   *fg = t;            --> *fg = 2
  return f (or return 3)

里面的乐趣(4, fg)

t = fun(3, fg);   --> t = 3
  /* After fun(3, fg) is called, fun(4, fg) does following */
   f = t + *fg;       -->  f = 3 + 2 = 5
   *fg = t;            --> *fg = 3
   return f (or return 5)

里面的乐趣(5, fg)

t = fun(4, fg);   -->  t = 5
  /* After fun(4, fg) is called, fun(5, fg) does following */
   f = t + *fg;       -->  f = 5 + 3 = 8
   *fg = t;            --> *fg = 5
   return f (or return 8 )

最后打印 fun(5, &x) 返回的值,所以屏幕上打印了 8