如何使用for循环使用php求和


How to sum numbers with php using for loop?

有人能帮我理解如何求和吗?

例如,我想使用For循环来对从1到10的所有数字求和:

'1+2+3+4+5+6+7+8+9+10=?' 

因为你特别提到了循环:

<?php
$start = 1;
$end = 10;
$sum = 0;
for ($i = $start; $i <= $end; $i++) {
    $sum += $i;
}
echo "Sum from " . $start . " to " . $end . " = " . $sum;

是的,这很容易做到:

array_sum(range(1, 10))

$sequence = array(1,2,3,4,5,6,7,8,9,10);
array_sum($sequence);

不确定我是否理解这个问题,但

$sum = 0;
for ($i = 1; $i <= 10; $i++) {
   $sum += $i;
}
echo 'The sum: ' . $sum;

应将介于1和10之间的数字求和到$sum变量中。

这样做。。。你有很多选择来做这个

$a=0;
for($i=0;$i==10;$i++)
{
    $a=$a+$i;
}
echo 'Sum= ' . $a ;

事实上,使用循环是效率最低的方法。这是一个算术序列,可以使用以下公式计算:

S = n*(a1+an)/2 

其中a1是第一个元素,an是最后一个元素,其中n是元素的数量。

// for 1..10 it would be: 
$sum = 10*(1+10)/2; 
// for 1..2000 it would be:
$sum = 2000*(1+2000)/2; 
// u can use the same formula for other kinds of sequences for example:
// sum of even numbers from 2 until 10:
$sum = 5*(2+10)/2; // 5 elements, first is 2, last is 10

这样尝试:

<form method="post">
Start:<input type="text" name="a">
End: :<input type="text" name="b">
<input type="submit" >
</form>
<?php
$start = $_POST['a'];
$end = $_POST['b'];
$sum = 0;
for ($i = $start; $i <= $end; $i++) {
    $sum += $i;
}
echo "<h2>Sum from " . $start . " to " . $end . " = " . $sum;

?>
<?php
    $array = array(1,2,3,4,5,6,7,8,9,10);  
    $count = count($array);
    $sum = 0;
    for($i=0;$i<$count;$i++){
      $sum  += $array[$i];
    }
    echo $sum ;
?>

使1+2+3+4+5=?通过递归函数

<?php
    $n=1;
    echo Recursion($n);
    function Recursion($n){
        if ($n <=5){
            if($n<5){
                echo "$n+";
            }
            else echo "$n=";
        return $n+Recursion($n+1);
        }
    }
    ?>