【问题标题】:Creating an inflation calculator in PHP在 PHP 中创建通货膨胀计算器
【发布时间】:2012-09-17 13:13:10
【问题描述】:

这是我目前拥有的代码,一切都按预期工作,但是,累计总数不起作用,我很肯定我在做一些绝对愚蠢的事情。

assume period = 20
assume inflation = 3
assume nightlycost = 100
assume nights = 7

$yearlycost = $nightlycost*$nights;
while ($period > 0) {
    $period = $period-1;
    $yearlyincrease = ($inflation / 100) * $yearlycost;
    $nightlyincrease = ($inflation / 100) * $nightlycost;
    $nightlycost = $nightlycost + $nightlyincrease;
    $yearlycost = ($yearlycost + $yearlyincrease) + $yearlycost;
}

Result:
Nightly Hotel Rate in 20 years: $180.61 - <?php echo round($nightlycost, 2); ?> correct

Weekly Hotel Rate in 20 years: $1264.27 - <?php echo round($nightlycost, 2) * 7; ?> correct

Total cost to you over 20 years: $988595884.74 - <?php echo round($yearlycost, 2); ?> incorrect

除了每年的累积成本外,一切都按预期正确输出。它应该取上一年的成本并加上该年的成本+通货膨胀。

示例:第一年是 700,所以第二年应该是 700 + 700 + 21(21 是 3%,即当年的通货膨胀率)。因此,第二年的累计总数为:1421。第三年将是 1421 + 721(去年的总数)+ 721 的 3%。

希望这足以让您明白我哪里出错了。谢谢!

【问题讨论】:

  • 您是否需要像现在一样开始您的$yearlycost var,然后将其乘以 52 周?现在看起来像每周费用......`晚数*每晚费用`
  • 它实际上是一个假期成本计算器 - 所以 7 晚是用户选项,这就是为什么我将其设置为 nightlycost*nights,即;该用户一年有 7 晚度假。
  • 每年的成本总是 700,而不是 721——与通货膨胀率无关。如果您想将其纳入产品价格,则应将该百分比添加到每晚的成本中,这样它们将乘以已经考虑的通货膨胀成本。

标签: php cumulative-sum


【解决方案1】:

我很难理解你的代码哪里出错了,但我的直觉是你的循环体的最后一行应该有一个乘法。

基本上,您有一个时期 0 的基本成本。然后您想计算 X 年后给定通货膨胀的累积成本。那个成本是(伪代码)

base = nightlycost + nights
infl = 1.03
cumulative = base + base*infl + base*infl^2 + base*infl^3 + ... + base*infl^periods

最后一个表达式可以简化为

cumulative = base*((1-infl^periods)/(1-infl))

(这里根据公式 4 成立:http://mathworld.wolfram.com/ExponentialSumFormulas.html

例子:

$base = 100*7;
$infl = 1.03; // 3% of inflation/year

$periods = 2;
$cumulative = $base * (1-pow($infl, $periods))/(1-$infl);
print "Cumulative cost after $periods is $cumulative\n";

// Let's try with three periods.
$periods = 3;
$cumulative = $base * (1-pow($infl, $periods))/(1-$infl);
print "Cumulative cost after $periods is $cumulative\n";

输出:

Cumulative cost after 2 is 1421
Cumulative cost after 3 is 2163.63

【讨论】:

    猜你喜欢
    • 2023-02-24
    • 2021-09-24
    • 2021-08-17
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多