用来计算复利的简单程序,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。在此处输入带有calculateyears == 1,这是在输入有问题的if语句时。现在,在执行此return语句中的if之后,将在递归停止的上一级继续执行。在递归调用之后,它在else块内。当您检查years的值时,您会看到在执行1中的2后,它从return变为if

关于java - 简单的Java递归,无法预测的程序行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33698898/

10-11 16:48