Java 递归方法中的逻辑错误

Java 递归方法中的逻辑错误,java,recursion,Java,Recursion,我想写一个程序,用递归的方法来计算,如果每个月都有2%的利息加上同样的金额(用户输入),达到1000万的总投资目标需要多少个月。问题是该方法返回计数器太早,因此我的“月”输出不准确。我猜我的最后一个else语句是错误的,或者我的计数器放置不正确 这是我的密码 import java.util.Scanner; public class MoneyMakerRecursion { public static int counter = 0; publi

我想写一个程序,用递归的方法来计算,如果每个月都有2%的利息加上同样的金额(用户输入),达到1000万的总投资目标需要多少个月。问题是该方法返回计数器太早,因此我的“月”输出不准确。我猜我的最后一个else语句是错误的,或者我的计数器放置不正确

这是我的密码

   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);}
        }
    }

你们错过的重要一点是,你们每个月的投资在所有月份都是一样的。因此,它应该是静态变量

第二点,你们把投资加到总投资中,这是该方法的局部变量。这不是一个月的实际投资。它是传递给该函数的一个值,每个月都会发生变化(请考虑此语句的代码)

请参阅下面的工作代码

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);}
        }
    }
结果

Enter your monthly investment: 
100000
It should take 55 month(s) to reach your goal of $10,000,000
这里是快照:这里每年考虑利息,因此将0.02月利息转换为0.24年利息


不,问题是你在每次迭代中都会将投资增加一倍,把它加到总投资中。很好,我同意你的逻辑+1。。。但是谁否决了这个问题?@TimBiegeleisen我否决了你的答案。对不起,先生,没有给你提供理由。希望这个答案能让你满意为什么我否决了你的建议answer@JBNizet请把问题通读一遍。你会遇到这样一句话:“如果相同数量的钱(由用户输入)被投资”,你的逻辑对我来说很有意义。但是出于某种原因。它仍然没有达到预期的效果。参考一下这个计算器。financialmentor(dot)com/计算器/储蓄账户计算器。100k的输入应产生93。但是它的结果是55。嘿,我将添加快照