duanjian4698 2014-09-25 13:25
浏览 29
已采纳

为什么这个递归函数会像这样工作?

I am trying to learn recursion and have written a function that takes a number and count it down to zero and then count it up to the original number again, the function works, but what I don't understand is why it works as it does. I understnad why the first print after the else statement prints: "5 4 3 2 1" and then the number is 0 and the if statement prints: "0". It is after this scenario I don't understand since now the function enters the second print after the else statement and prints: "1 2 3 4 5" which is very strange to me. I would really appreciate if someone could explain this to me.

<?php
function rec_downandup($num){
    if($num == 0){
        print '0 ';
    }else{
        print $num.' ';
        rec_downandup($num-1);
        print $num.' ';
    }
}
rec_downandup(5);
?>

Output

5 4 3 2 1 0 1 2 3 4 5
  • 写回答

3条回答 默认 最新

  • duan19805 2014-09-25 13:29
    关注

    When you take a closer look, it should become clear.

    print $num.' ';
    rec_downandup($num-1);
    print $num.' ';
    

    For your first input, you will get

    print 5.' ';
    rec_downandup(4);
    print 5.' ';
    

    and after that call it is

    print 5.' ';
    print 4.' ';
    rec_downandup(3);
    print 4.' ';
    print 5.' ';
    

    So it appears the functions counts down and up, but actually it just counts down and places each number twice - the second time in reverse order so it appears to be counting up.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)