我試圖編寫一個使用遞歸方法的程序來計算在投入相同數量的錢(由用戶輸入)時投入總共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);}
}
}
沒有,問題是,您將每次迭代的投資翻倍,將其添加到總計中。 –