用来计算复利的简单程序,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并没有帮助。
最佳答案
在else
的任何呼叫上都进入years > 1
分支,尤其是对于years == 2
。在此处输入带有calculate
的years == 1
,这是在输入有问题的if
语句时。现在,在执行此return
语句中的if
之后,将在递归停止的上一级继续执行。在递归调用之后,它在else
块内。当您检查years
的值时,您会看到在执行1
中的2
后,它从return
变为if
。
关于java - 简单的Java递归,无法预测的程序行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33698898/