C递归问题

Bip*_*mar 4 c recursion

我有一个关于递归函数的查询.这是我的计划.

#include <stdio.h>

int fun(int);

int main(void)
{
    int x;
    int k=3;
    x = fun(k);
    printf("%d\n",x);
    return 0;
}

int fun(int a)
{
    int f;
    if(a == 1) return (1);
    f = 2 + fun(a-1);
    return (f);
}
Run Code Online (Sandbox Code Playgroud)

我有价值K=3的地方STEP-6.在STEP-7函数fun(k)中将K的值传递给被调用的函数STEP-11 int fun(int a).在被调用函数中,fun(int a)递归发生了2次,即(3,2)得到的值a=1.后面的STEP-14,值f变为3,因为f = 2 +(fun(1)= 1).在STEP-16它中返回被调用函数即fun(int a)=3.应该打印出来的价值x is 3,不太可能.它是x = 5

Sou*_*osh 5

我们来检查一下呼叫顺序fun()吧?

参数值为3,从.开始main()

  • x = fun(3)
    • f = 2 + fun(2);
      • f = 2 + fun(1);

现在,让我们以相反的顺序检查返回值.

  1. 最后一个电话,fun(1)返回1,
  2. 所以第二个电话fun(2),返回2 + 13,
  3. 最后一次通话,fun(3)返回2 + 35

那是来自的电话main().所以,在main(),x得到一个值5.