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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭