本人自学php,遇到递归算法问题,请各位高手帮忙解答下。

WBOY
Release: 2016-06-23 13:59:10
Original
985 people have browsed it

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 '
'; //这里去掉这里你又输出了一遍
}

这样看的清楚些

<?phpfunction display($i){  echo __LINE__ .": $i<br>";  $i=$i-2;  if($i>0){    display($i);  }  echo __LINE__ .": $i<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

这样就可以了。

<?phpfunction display($i){    echo $i.'<br>';    $i>0? display($i-2) : '';}display(10);?>
Copy after login

弄明白了,感谢各位指教。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!