递归方法中的逻辑错误
问题描述:
我试图编写一个使用递归方法的程序来计算在投入相同数量的钱(由用户输入)时投入总共1000万美元的目标需要多少个月每月增加2%的利息。问题是该方法太早返回计数器,所以我的“月”输出不准确。我的猜测是我最后的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
没有,问题是,您将每次迭代的投资翻倍,将其添加到总计中。 –