Home > Backend Development > PHP Tutorial > 本人自学php,遇到递归算法有关问题,请帮忙解答下

本人自学php,遇到递归算法有关问题,请帮忙解答下

WBOY
Release: 2016-06-13 11:54:20
Original
886 people have browsed it

本人自学php,遇到递归算法问题,请各位高手帮忙解答下。
function display($i){
echo $i;
echo '


';
   $i=$i-2;
   if($i>0){
     display($i);
   }
    echo $i;
    echo '
';
}
  display(10);
?>

按输出结果的值应该是 10  8   6   4   2    为什么又返回执行 0    2    4    6   8  不明白为什么?
10
8
6
4
2
0
2
4
6
8

------解决方案--------------------

执行顺序为红色箭头所示
------解决方案--------------------
function display($i){
echo $i;
echo '
';
   $i=$i-2;
   if($i>0){
     display($i);
   }
    echo $i;
    echo '
';
 //这里去掉这里你又输出了一遍
}

------解决方案--------------------
这样看的清楚些
<?php<br />function display($i){<br />  echo __LINE__ .": $i<br>";<br />  $i=$i-2;<br />  if($i>0){<br />    display($i);<br />  }<br />  echo __LINE__ .": $i<br>";<br />}<br />display(10);
Copy after login
3: 10
3: 8
3: 6
3: 4
3: 2
8: 0
8: 2
8: 4
8: 6
8: 8
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template