0

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

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%。

希望这足够清楚,您可以看到我哪里出错了。谢谢!

4

1 回答 1

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
于 2012-09-17T13:31:55.967 回答