dongting7352
dongting7352
2014-11-02 12:37
浏览 138
已采纳

如何使用for循环使用php对数字求和?

I am learning PHP. Can someone help me understand how to sum numbers?

For example, I want to use a for loop to sum all numbers from 1 to 10:

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

图片转代码服务由CSDN问答提供 功能建议

我正在学习PHP。 有人可以帮我理解如何对数字求和吗?

例如,我想使用for循环对1到10之间的所有数字求和:

 '1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 =?'  
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

8条回答 默认 最新

  • duanchi4184
    duanchi4184 2014-11-02 12:40
    已采纳

    Since you specifically said for loop:

    <?php
    
    $start = 1;
    $end = 10;
    
    $sum = 0;
    for ($i = $start; $i <= $end; $i++) {
        $sum += $i;
    }
    
    echo "Sum from " . $start . " to " . $end . " = " . $sum;
    
    点赞 评论
  • dongshi1215
    dongshi1215 2014-11-02 12:41

    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);
    
    点赞 评论
  • dongqiangse6623
    dongqiangse6623 2014-11-02 12:42

    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 ;
    
    点赞 评论
  • douchen7555
    douchen7555 2014-11-02 12:42

    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.

    点赞 评论
  • dsadsa123111
    dsadsa123111 2014-11-02 12:42

    When learning PHP from scratch, you should probably start with some tutorials.

    You could start with a tutorial on variables, a tutorial on operators and then a tutorial on for loops.

    You should be able to solve this problem on your own afterwards. Doing this on your own will give you a much better learning experience, than just copying other answers here.

    点赞 评论
  • ds261634878
    ds261634878 2017-03-31 20:34

    for ($i = 0; $i <= 10; $i++) {

    echo $i;

    }

    点赞 评论
  • drl9940
    drl9940 2017-05-12 05:43

    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;
    
    
    ?>
    
    点赞 评论
  • dqp4933
    dqp4933 2019-07-23 10:41

    Make 1+2+3+4+5 = ? by recursion function

    <?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);
            }
        }
        ?>
    
    点赞 评论

相关推荐