dongshan7060 2015-06-16 10:22
浏览 280
已采纳

PHP总结了从0到200的所有偶数

I tried to sum up all even numbers from 0 to 200 and I found 2 possible working ways, however the third method (the most efficient one) gives me a headache. Here's what I did so far:

First method:

$total = 0;
$number = 0;

while ($number < 200)
{
    if ($number % 2 == 0)
    {
        $total = $total + $number;
    }
    $number++;
}

echo $total;

Second method:

    $total = 0;
    for($number = 0; $number < 200; $number+=2) 
    {
        $total += $number;
    }
echo $total;

Third method (can't get it to work)

echo array_sum(range(1,200,2));

How should I change my last method so that it works as intended?

Edit: Seems that none of the methods work: the output should be 10100 but it is 9900 for the first two methods and 10000 for the third.

  • 写回答

3条回答 默认 最新

  • dqv2743 2015-06-16 10:29
    关注

    You need to use

    echo array_sum(range(0,198,2));
    

    or

    echo array_sum(range(0,199,2));
    

    Its because the above function will sum up the values upto 200 whereas within your while and for loop will count upto 198 only as you have specifically defined

    $number < 200
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错