我只是做了一些用PHP递归练习和我有点通过以下的输出困惑:为什么这个PHP代码段的行为如此?
function calc($numTimes, $i, $total) {
if (!$i && !$total) {$i = 1; $total = 1;}
if ($i <= $numTimes) {
$total = $total*2;
$i++;
calc($numTimes, $i, $total);
}
echo $total.'+'.$i.'<br />';
}
calc(5);
运行它之前,我会一直假设输出为32 + 6。但是,这是我得到:
32+6
32+6
16+5
8+4
4+3
2+2
我不明白。输出不仅比我预期的要长5行,而是增加了总数,而不是从中删除?另外,如果我添加一个休息;回声后,它只返回32 + 6,这在某种程度上似乎是相关的。但是,当我更改代码以便它使用return $ total;而不是回声:
function calc($numTimes, $i, $total) {
if (!$i && !$total) {$i = 1; $total = 1;}
if ($i <= $numTimes) {
$total = $total*2;
$i++;
calc($numTimes, $i, $total);
}
return $total.'+'.$i.'<br />';
}
$r = calc(5);
echo $r;
这就是被打印出来:
2+2
我有点困惑,并希望有人能帮助我明白是怎么回事。
'$ sum'是什么?你想做什么?如果你的代码被破坏了,我该如何解决? –