【问题标题】:Php subtraction and adding sumphp减法和加法
【发布时间】:2017-11-01 12:36:07
【问题描述】:

我必须在 php 上创建一个这样的总和

1+2-3+4-5+6-7+8-8+10

到目前为止,我得到了这个:

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

我知道 php 代码是加法,但我不确定如何在加法和减法之间切换,因为总和仍在继续。感谢您回答我的询问。

【问题讨论】:

  • 8-8 应该是8-9
  • 您好,欢迎来到stackoverflow?请访问How to askAsking .... 为什么不把它分解成只有加法和只有减法呢?就你所知道的,这绝对是可能的!你有没有在网上搜索过如何在 php 中分支?
  • 您已收到三个可用的答案。如果您不养成接受和赞成答案的习惯,那么人们将来帮助您的可能性就会降低。

标签: php sum addition


【解决方案1】:

逻辑应该是,加 1 后,每个偶数相加,每个奇数相减。为此,您需要使用模运算符。

$start = 1;
$n=10;
$sum = 0;
for($i=$start; $i <=$n; $i++){
    // for 1 or any even number (use modulo operator to check remainder when dividing by 2), add to sum
    if($i == 1 || $i%2 == 0)
    {
        $sum += $i;
    }
    // for any other number (any non-1 odd number), subtract from sum
    else
    {
        $sum -= $i;
    }
}
echo "sum from " . $start . " to " . $n . " = " . $sum;

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多