任何人都可以帮我解决这个程序的执行顺序

时间:2013-11-18 10:05:15

标签: c recursion

我试图预测这个程序的输出:

#include
void fun(int x)
{
  if (x > 0)
  {
    fun(--x);
    printf("%d\t", x);
    fun(--x);
  }
}

int main()
{
  int a = 4;
  fun(a);
  getchar();
  return 0;
}

该程序的输出是:

0 1 2 0 3 0 1

我知道很难用术语来解释,但我想要知道的是,当4作为参数传递而不是首先声明fun(4--),即执行fun(3)时,所以从这里调用制作fun(3)或打印3然后执行fun(3--)语句 基本上我对以下序列感到困惑:

fun(--x);
printf("%d\t", x);
fun(--x);

执行这3个陈述。

3 个答案:

答案 0 :(得分:5)

会发生什么:

call to fun(4)
    -> call to fun(3)
        -> call to fun(2)
            -> call to fun(1)
                -> call to fun(0) which prints nothing and returns
                -> printing 0
                -> call to fun(-1) which prints nothing and returns
            <- execution returns to fun(2), where 1 is printed
        -> in fun(3) 2 is printed and fun(1) called
            -> fun(1) prints 0
            <-
        <-
    -> in fun(4) 3 is printed and fun(2) called
        -> fun(2) prints 0 1
通常,使用基本参数观察调用的行为是一种很好的做法,即在您的情况下:
  • fun(x)其中x <= 0 - 跳过条件,返回,没有打印
  • fun(1) - 调用fun(0),打印0,调用fun(-1) - 即打印0
  • fun(2) - 调用fun(1)打印0,打印1,调用fun(0) - 即打印0 1

然后你可以在纸上画出执行的流程,当你看到这三个中的一个时,你已经知道了结果。就像我上面的例子一样,最后当我看到fun(2)时,我看到了fun(2)被叫之前发生的事情并看到了“啊是​​的,fun(2)打印0 1”。希望这会有所帮助;)

答案 1 :(得分:2)

当你打电话给乐趣(4)时:

  1. 它称之为乐趣(3)
  2. fun(3)call fun(2)
  3. fun(2)call fun(1)
  4. fun(1)call fun(0)
  5. fun(0)结束无所事事
  6. 它回归有趣(1),其中x从-x变为0并显示它,并调用fun(-1),它什么都不做。现在好玩(1)完成了它的工作
  7. 它回归有趣(2),显示1并调用fun(0),它什么都不做。现在好玩(2)完成了它的工作。
  8. 它回归有趣(3),显示2并调用fun(1)。如上所述,fun(1)显示0。
  9. 它回归有趣(4),显示3并调用fun(2)。如上所述,fun(2)显示0 1。
  10. 我希望这能为你澄清一些事情。

答案 2 :(得分:0)

流程:

main():
 fun(4):
 x is 3 and the following are called-
  fun(3):
  x is 2 and-
   fun(2):
   x is 1 and-
    fun(1):
    x is 0
    the call to fun(0) returns, after having bottomed out, PRINT 0.
    calls fun(-1)
    call returns
   when fun(1) returns, PRINT 1
   x is 0
  PRINT 2
  fun(1)
   x is 0
   call to fun(0) returns
   PRINT 0
   call to fun(-1) returns
 PRINT 3
 fun(3)
  x is 2
  fun(2)
   x is 1
   fun(0) returns
   PRINT 0
  PRINT 1

我可能出错了,但这就是流程。