【发布时间】: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);}
}
}
【问题讨论】:
-
不,问题是每次迭代都会使投资翻倍,将其添加到总数中。