我正在尝试制作一个计算每年利息的递归程序.它会提示用户启动金额(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);
}
}
Run Code Online (Sandbox Code Playgroud)
我冒昧地用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
Run Code Online (Sandbox Code Playgroud)
显然,这是不对的.首先,返回行也重新应用计算....这是重写方法:
static private double calculateInterest2(double start, double rate, int duration)
{
if (0 == duration) {
return start;
} else {
return (1+rate) * calculateInterest2(start, rate, duration - 1);
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,此方法使用此输出检出:
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
Run Code Online (Sandbox Code Playgroud)
对我来说听起来更合适.