计算复利的琐碎程序,I = P(1 + n)^ y。
public class Interest {
public static void main(String[] args){
double sum = calculate(1000,10,3);
System.out.println(sum);
//sanity check, using non-recursive formula:
double amt = 1000*(Math.pow(1 + 0.1, 3));
System.out.println(amt);
}
public static double calculate(double initialAmount, double interest, int years){
double yearly = initialAmount + initialAmount*(interest/100);
System.out.println("calculate is called with P = " + initialAmount + ", interest = "+interest+", and years = " + years);
System.out.println("This year's amount: "+yearly);
if (years <= 0){
return initialAmount;
}
if (years == 1){
return yearly;
}
else {
return yearly + calculate(yearly, interest, years - 1);
}
}
}
输出如下(注意YEARLY正确计算但未按预期返回):
debug:
calculate is called with P = 1000.0, interest = 10.0, and years = 3
This year's amount: 1100.0
calculate is called with P = 1100.0, interest = 10.0, and years = 2
This year's amount: 1210.0
calculate is called with P = 1210.0, interest = 10.0, and years = 1
This year's amount: 1331.0
3641.0
1331.0000000000005
当我调试时,执行按预期输入if(years == 1),但还进入以下else块。它如何进入两个分支?请指教;我一直绞尽脑汁,重新启动电脑,NetBeans没有帮助。
答案 0 :(得分:1)
您在多年之后没有进入else块== 1 if block,您只需每年为每次递归调用添加一次。
将else块中的return语句更改为
return calculate(yearly, interest, years - 1)
这
return yearly + calculate(yearly, interest, years - 1)
答案 1 :(得分:1)
不,执行后如果阻止,则不会进入else块。这不可能。如果它看起来那样,那么你似乎误解了你的调试器。请注意,在终端之后,执行将通过前面堆栈中的else语句退回。但它不会进入。只退一步。
结果累积在第一个参数中,不需要在方法的最后一行添加annual的值。逻辑也可以稍微简化一下:
if (years == 1){
return yearly;
}
return calculate(yearly, interest, years - 1);
答案 2 :(得分:0)
在else
的任何通话中输入years > 1
分支,尤其是years == 2
。在那里,您使用calculate
拨打years == 1
,这是您输入相关if
语句的时间。现在,在执行此return
语句中的if
之后,执行将在其停止的递归的先前级别上继续执行。在递归调用之后,这在else
块内。当您检查years
的值时,在1
执行2
后,您会看到它从return
更改为if
。