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条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊