答案是8但是怎么样?

时间:2014-12-05 19:22:42

标签: c recursion

以下代码如何运作?

#include <stdio.h>
#include <conio.h>
void main () {
    int n = 6, d;
    int func (int n) {
        int x, y;
        if (n <= 1)
            return n;
        x = func (n - 1);
        y = func (n - 2);
        return (x + y);
    }
    d = func (6);
    printf ("%d", d);
}

答案是8但不知道为什么?请解释一步一步。

2 个答案:

答案 0 :(得分:2)

让我们为func(n)构建一个执行树。如果使用n <= 1调用它,则会返回n。否则,它返回func(n-1)+func(n-2)

所以,

func(6)=
func(5)+func(4)=
func(4)+func(3)+func(3)+func(2)=
func(3)+func(2)+func(2)+func(1)+func(2)+func(1)+func(1)+func(0)=
func(2)+func(1)+func(1)+func(0)+func(1)+func(0)+func(1)+func(1)+func(0)+func(1)+func(1)+func(0)=
func(1)+func(0)+func(1)+func(1)+func(0)+func(1)+func(0)+func(1)+func(1)+func(0)+func(1)+func(1)+func(0)=
1+0+1+1+0+1+0+1+1+0+1+1+0=
8

答案 1 :(得分:1)

递归函数通常以对递归函数的新用户模糊的方式工作。学习递归函数逻辑的最佳方法之一是查看实际发生的事情。这就是为什么你经常听到递归函数比普通函数更不易阅读的原因。看看实际流程:

//how the code is working?
#include <stdio.h>
//#include <conio.h>
int main () {
    int n = 6, d;
    int func (int n) {
        printf (" entering func (%d)\n", n);
        int x, y;
        if (n <= 1)
            return n;
        x = func (n - 1);
        printf ("  x = %d\n", x);
        y = func (n - 2);
        printf ("  y = %d\n", y);
        printf ("    returning (%d + %d) = %d\n", x, y, x + y);
        return (x + y);
    }
    d = func (n);
    printf ("%d", d);
    return 0;
}

<强>输出:

$ ./bin/fun6
 entering func (6)
 entering func (5)
 entering func (4)
 entering func (3)
 entering func (2)
 entering func (1)
  x = 1
 entering func (0)
  y = 0
    returning (1 + 0) = 1
  x = 1
 entering func (1)
  y = 1
    returning (1 + 1) = 2
  x = 2
 entering func (2)
 entering func (1)
  x = 1
 entering func (0)
  y = 0
    returning (1 + 0) = 1
  y = 1
    returning (2 + 1) = 3
  x = 3
 entering func (3)
 entering func (2)
 entering func (1)
  x = 1
 entering func (0)
  y = 0
    returning (1 + 0) = 1
  x = 1
 entering func (1)
  y = 1
    returning (1 + 1) = 2
  y = 2
    returning (3 + 2) = 5
  x = 5
 entering func (4)
 entering func (3)
 entering func (2)
 entering func (1)
  x = 1
 entering func (0)
  y = 0
    returning (1 + 0) = 1
  x = 1
 entering func (1)
  y = 1
    returning (1 + 1) = 2
  x = 2
 entering func (2)
 entering func (1)
  x = 1
 entering func (0)
  y = 0
    returning (1 + 0) = 1
  y = 1
    returning (2 + 1) = 3
  y = 3
    returning (5 + 3) = 8