I'm just doing some recursion exercises in PHP and I'm a bit baffled by the output 开发者_如何学Cof the following:
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);
Before running it I would've assumed the output to be 32+6. However, this is what I get:
32+6
32+6
16+5
8+4
4+3
2+2
I don't get it. The output is not only 5 lines longer than I would've expected it to be, but instead of incrementing the total, it's removing from it? Also, if I add a break; after the echo, it only returns 32+6, which somehow seems relevant. However, when I change the code so that it uses return $total; instead of echo:
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;
This is what gets printed out:
2+2
I'm a bit confused and hoping someone can help me understand what's going on here.
you are not doing anything with the recursive call. the line:
calc($numTimes, $i, $total);
might calculcate a value, but does nothing with it. notice that the returned value is never saved. you would have to fetch it:
$res = calc($numTimes, $i, $total);
and then keep going with $res
i think what you meant is:
function calc($numTimes, $i = 0, $total = 0) {
if (!$i && !$total) {$i = 1; $total = 1;}
if ($i <= $numTimes) {
$total = $total*2;
$i++;
return calc($numTimes, $i, $total);
}
return $total.'+'.$i.'<br />';
}
echo calc(5);
In your first example, calc()
is called inside itself conditionally, hence it's looping and outputting numerous results (5 calls to echo).
In your second example, you have set a variable to be the result of the return value of calc()
. It is still looping, but the result is overridden each time. So you have one result showing (echo is called once).
You just have a typo, using $sum
instead of $total
in the first if
clause.
精彩评论