【问题标题】:Logic error in Recursive method递归方法中的逻辑错误
【发布时间】:2017-04-03 00:19:20
【问题描述】:

我正在尝试编写一个程序,该程序使用递归方法来计算如果以 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);}
        }
    }

【问题讨论】:

  • 不,问题是每次迭代都会使投资翻倍,将其添加到总数中。

标签: java recursion


【解决方案1】:

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

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

请参阅下面的工作代码。

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 我对你的回答投了反对票。对不起先生,没有给你理由。希望这个答案能满足你为什么我不赞成你的答案
  • @JBNizet 请回答问题。你会遇到这条线“如果投资相同数量的钱(由用户输入)”
  • 你的逻辑对我来说很有意义。然而由于某种原因。它仍然没有达到预期的结果。请参阅此计算器以获取参考。 Financialmentor(dot)com/计算器/储蓄账户计算器。 100k 的输入应该会产生 93。但它会产生 55。
  • 嘿,我会添加快照
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
相关资源
最近更新 更多