我正在尝试制作一个递归程序来计算每年的利息,它提示用户输入启动金额(1000),利率(10%)和年数(1)。(括号内为示例)

手动地,我意识到利息来自公式YT(1 + R)-----第一年的利息是1100。

第二年YT(1 + R / 2 + R2 / 2)// R平方

第二年YT(1 + R / 3 + R2 / 3 + 3R3 /)// R立方

如何编写一个计算利息的递归程序?下面是我尝试的功能

//编辑后最新

double calculateInterest2(double start, double rate, int duration)
{
    if (0 == duration) {
        return start;
    } else {
        return (1+rate) * calculateInterest2(start, rate, duration - 1);
    }
}

最佳答案

我随意使用Java测试您的函数(语法相似),并且返回了奇怪的结果。这是我得到的:

calculateInterest2(1000, .1, 0); // = 1000.0
calculateInterest2(1000, .1, 1); // = 1200.0
calculateInterest2(1000, .1, 2); // = 1420.0
calculateInterest2(1000, .1, 3); // = 1662.0
calculateInterest2(1000, .1, 4); // = 1928.2

显然,这是不对的。首先,返回行也正在重新应用计算。...这是方法的重写:
static private double calculateInterest2(double start, double rate, int duration)
{
    if (0 == duration) {
        return start;
    } else {
        return (1+rate) * calculateInterest2(start, rate, duration - 1);
    }
}

如您所见,此方法通过以下输出进行 check out :
calculateInterest2(1000, .1, 0); // = 1000.0
calculateInterest2(1000, .1, 1); // = 1100.0
calculateInterest2(1000, .1, 2); // = 1210.0
calculateInterest2(1000, .1, 3); // = 1331.0
calculateInterest2(1000, .1, 4); // = 1464.1000000000001

听起来对我来说更正确。

关于c++ - 递归程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2894859/

10-12 21:48