递归方法中的逻辑错误

时间:2017-04-02 14:59:58

标签: java recursion

我正在尝试编写一个程序,该程序使用递归方法来计算如果以2%的利息投入相同数量的资金(由用户输入),则达到总投资1000万的目标需要多少个月每月补充一次。问题是该方法过早地返回计数器,因此我的“月”输出是不准确的。我的猜测是我的最后一个声明错误或我的计数器放错了

继承我的代码

   import java.util.Scanner;
    public class MoneyMakerRecursion {
        public static int counter = 0;
        public static void main(String[] args) {
            //Variables declared
            Scanner userInput = new Scanner(System.in);
            double investment;
            //User is prompted for input
            System.out.println("Enter your monthly investment: ");
            investment = userInput.nextInt();
            //Method is called
            Sum(investment);
            //Results from recursive method output 
            System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
        }
        //recursive Method
        public static double Sum(double investment) {
            counter++;
            double total = (investment * 0.02) + investment;
            if(total >= 10000000) {return counter;}
            else {return Sum(investment+total);}
        }
    }

1 个答案:

答案 0 :(得分:1)

您错过的重要一点是您的月度投资在所有月份都是相同的。因此它应该是静态变量。

第二点,您将总投资添加到该方法的局部变量。这不是一个月的实际投资。它传递给该函数的值,每个月都会更改(请考虑此语句的代码)

见下面的工作代码。

[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

结果

import java.util.Scanner;
    public class MoneyMakerRecursion {
        public static int counter = 0;
        public static double investment = 0;
        public static void main(String[] args) {
            //Variables declared
            Scanner userInput = new Scanner(System.in);
            //User is prompted for input
            System.out.println("Enter your monthly investment: ");
            investment = userInput.nextInt();
            //Method is called
            Sum(investment);
            //Results from recursive method output 
            System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
        }
        //recursive Method
        public static double Sum(double totalInvestment) {
            counter++;
            double total = (totalInvestment* 0.02) + totalInvestment;
            if(total >= 10000000) {return counter;}
            else {return Sum(total+investment);}
        }
    }

以下是快照:此处每年考虑利息,因此将0.02个月利息转换为每年利息为0.24

enter image description here