wordpress CMS主题 微信
Home > 网站建设 > What is a recursive function and use it to calculate the factorial of 5

What is a recursive function and use it to calculate the factorial of 5

高时银博客 网站建设 点击: 2,295 次 0 0
  • 标签:
  • The so-called recursive function, is from the calling function, the in vivo functiondirectly or indirectly call their own. But the recursive function calls need to set upsince the call from the conditions, if the condition is satisfied, then call the function itself, if it is not satisfied then terminated since the call to this function,then the main control flow right back to function on a layer to perform. Here, to find out the function through an example.

    <?phpfunction table($a){echo $a." ";if($a>0)  / / self call condition

    {

    table($a-1);  / / self called variable value minus 1

    }

    else

    {

    echo "<-->";

    }

    echo $a." ";

    }

     

    table(10);

    ?>

    The output is the result of: 109876543 210 01234567 8910 < - >

    You may be a little confused, in front of 109876543 210 can be well understood,but behind the 01234567 8910 is how come? This is because in every time hecalled, since subsequent calls to $a. "echo"; not implemented, it will last from aself call begins after the 1 1 to operational display, until first since the call ended.Finally, a self call, namely $a=1, in this way, table ($a-1) since the call $a valuebecomes 0; and so on, the second since the call, $a=2, also can output 1......Until first since the call.

    Here is the recursive function to calculate the factorial of 5:

    <?phpfunction demo($a){

    if($a > 1)

    $r=$a*demo($a-1);

    else

    $r=$a;

    return $r;

    }

    echo demo(5);

    ?>

    The output is the result of: 120 (1*2*3*4*5 results).


    文章作者:高时银博客
    本文地址:http://wanlimm.com/77201404061863.html
    版权所有 © 转载时必须以链接形式注明作者和原始出处!

    目前还没有评论。赶快来坐沙发吧。

    发表评论