php 如何使用for循环用php对数字求和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26699365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sum numbers with php using for loop?
提问by Anton Papazov
I am learning PHP. Can someone help me understand how to sum numbers?
我正在学习 PHP。有人可以帮助我了解如何对数字求和吗?
For example, I want to use a for loop to sum all numbers from 1 to 10:
例如,我想使用 for 循环对从 1 到 10 的所有数字求和:
'1+2+3+4+5+6+7+8+9+10=?'
回答by Ananth
Since you specifically said for loop:
由于您专门说 for 循环:
<?php
$start = 1;
$end = 10;
$sum = 0;
for ($i = $start; $i <= $end; $i++) {
$sum += $i;
}
echo "Sum from " . $start . " to " . $end . " = " . $sum;
回答by felipsmartins
Yes, it is pretty easy to do:
是的,这很容易做到:
array_sum(range(1, 10))
or
或者
$sequence = array(1,2,3,4,5,6,7,8,9,10);
array_sum($sequence);
回答by Akhil Sidharth
this will do ... you have a lot of options to do this
这会做......你有很多选择来做到这一点
$a=0;
for($i=0;$i==10;$i++)
{
$a=$a+$i;
}
echo 'Sum= ' . $a ;
回答by Kakuriyo S
Not sure if I understand the question or not, but
不确定我是否理解这个问题,但是
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i;
}
echo 'The sum: ' . $sum;
Should sum the numbers between 1 and 10 into the $sum variable.
应该将 1 到 10 之间的数字相加到 $sum 变量中。
回答by Md Mahiuddin
<?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 ;
?>
回答by Shyful66
Try like this:
像这样尝试:
<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;
?>
回答by raqibnur
Make 1+2+3+4+5 = ? by recursion function
使 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);
}
}
?>
回答by Tsk Dynamo
for ($i = 0; $i <= 10; $i++) {
for ($i = 0; $i <= 10; $i++) {
echo $i;
回声 $i;
}
}