簡體   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