【问题标题】:Trying to add up numbers in PHP for loop尝试在 PHP for 循环中添加数字
【发布时间】:2016-09-22 12:49:55
【问题描述】:

我正在尝试将代码中输出的所有数字相加,我该怎么做?

$tall1 = 0;

for ($tall1=0; $tall1 <= 100; $tall1++) { 
    if ($tall1 % 3 == 0) {
        echo $tall1 . " ";
        $tall++;
    }
}

【问题讨论】:

  • 在开发和测试代码时,在脚本顶部使用error_reporting(E_ALL); ini_set('display_errors', 1);。你会看到 PHP 抱怨一个未定义的变量 $tall,这可能会让你的错误更容易被发现。
  • @RiggsFolly 当然......

标签: php for-loop


【解决方案1】:
$total = 0; //initialize variable

for ($tall1=0; $tall1 <= 100; $tall1++) { 
    if ($tall1 % 3 == 0) {
        echo $tall1 . " ";
        $total += $tall1; //add the printed number to the previously initialized variable. This is the same as writing $total = $total + $tall1;
    }
}

echo "total: ".$total; //do something with the variable, in this case, print it

关于您的初始代码的一些说明:

$tall1 = 0; //you don't need to do this, it is done by the for loop
for (
     $tall1=0; //this is where $tall1 is initialized
     $tall1 <= 100; 
     $tall1++ //this is where $tall1 is incremented every time
       ) { 
    if ($tall1 % 3 == 0) {
        echo $tall1 . " ";
        $tall++; //this variable is not used anywhere. If you meant $tall1, then you don't need to do this, it is done by the for loop. If you did not mean $tall1, but wanted to count how many times the if statement runs, then you need to initialize this variable (place something like $tall=0; at the top)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2016-01-16
    • 2017-08-23
    相关资源
    最近更新 更多