繁体   English   中英

解码功能更好地了解

[英]Decoding function to better understand

我正在重新访问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开发人员的人来说,它也是一个坚强的支柱。

您不了解循环的最后一部分。 现在实际上是这样的:

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

我对您的脚本进行了一些更改,以便它可以随时显示执行的操作。 如果我很难思考问题,我觉得做这种事情很有用。

$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;

让我们解释一下

$ 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM