对于递归:要先会写,再去理解
// ==题1:写一个sum($n),求1->n的和== //
function sum($n) {
for($sum=0,$i=1;$i<=$n;$i++) {
$sum += $i;
}
return $sum;
}
echo sum(100);
// ==进化== //
function sum2($n) {
return array_sum(range(1,$n));
}
echo sum2(100);
// ==递归计算1到100的和的规律== //
/*
sum(100) == ?
sum(99) + 100;
sum(99) == ?
sum(98) + 99;
sum(98) == ?
sum(97) + 98;
~
~
sum(2) == ?
sum(1) + 2;
sum(1) == ?
可以用递归
sum(100)->
sum(99) + 100;
sum(98) + 99 + 100;
sum(97) + 98 + 98 + 99 + 100;
~
~
*/
function sum3($n) {
if($n>1) {
return sum($n-1) + $n;
} else {
return 1;
}
}
echo sum3(100);