我正在重新访问PHP,并希望重新学习我缺乏的地方,我发现了一个问题,我无法理解以下代码,因为它应该根据测验输出6
,我得到了但是我把它分解成简单的部分并注释掉以便更好地理解,据我所知$ sum的值应该是4
,但是我做错了,也许我的故障是错的?
$numbers = array(1,2,3,4);
$total = count($numbers);
//$total = 4
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
//0+1 = 1
//0+2 = 2
//0+3 = 3
//0+4 = 4
if ($i < $total) {
$sum = $sum + $number;
//1st time loop = 0 < 4 false
//2nd time loop = 0 < 1 false
//3rd time loop = 0 < 2 false
//5th time loop = 0 < 3 false
//6th time loop = 4 = 4 true
//$sum + $number
//0 + 4
//4
}
}
echo $sum;
这是一个非常基本的问题,可能会得到投票,但对于想成为PHP开发人员的人来说,它也是一个强有力的支柱。
答案 0 :(得分:2)
你不理解循环中的最后一部分。它现在实际上是这样的:
if($i < $total) {
$sum = $sum + $number;
//1st time loop: $sum is 0. $sum + 1 = 1. $sum is now 1.
//2nd time loop: $sum is 1. $sum + 2 = 3. $sum is now 3.
//3rd time loop: $sum is 3. $sum + 3 = 6. $sum is now 6.
//4th time loop: it doesn't get here. $i (4) < $total (4)
//This is false, so it doesn't execute this block.
}
echo $sum; // Output: 6
答案 1 :(得分:1)
我稍稍修改了你的脚本,以便打印出它正在做的事情。如果我很难思考问题,我觉得做这种事很有用。
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$i = 0;
$j = 0;
foreach($numbers as $number) {
$i = $i + 1;
echo "Iteration $j: \$i +1 is $i, \$sum is $sum, \$number is $number";
if ($i < $total) {
$sum = $sum + $number;
echo ", \$i is less than \$total ($total), so \$sum + \$number is: $sum";
} else {
echo ", \$i is not less than \$total ($total), so \$sum will not be increased.";
}
echo '<br>'; // or a new line if it's CLI
$j++;
}
echo $sum;
答案 2 :(得分:0)
让我们解释
$ i的初始值为0但是当你开始循环时,你将它递增1,所以$ i的起始值是1.
检查条件时,您确实使用等号来检查最后一个值,无论您的起始值是否为1.所以很明显,您的循环必须运行少于总共1个。
$i = 0;
foreach($numbers as $number) {
$i += 1;
if ($i < $total)
$sum += $number;
}
echo $sum;
<强>分析强>
Step: 1 / 4
The value of $number is: 1 And The value of $i is: 1
Step: 2 / 4
The value of $number is: 2 And The value of $i is: 2
Step: 3 / 4
The value of $number is: 3 And The value of $i is: 3
当循环再次进行检查时,$ i的值增加1和4.因此尝试匹配条件if ($i < $total)
,其中$ i和$ total的值相等,所以它将返回false。所以循环只运行3次。
<强>结果强>
6