2017-04-02 116 views
1

我試圖編寫一個使用遞歸方法的程序來計算在投入相同數量的錢(由用戶輸入)時投入總共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);} 
     } 
    } 
+0

沒有,問題是,您將每次迭代的投資翻倍,將其添加到總計中。 –

回答

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

enter image description here

+0

很好的結果,我同意你的邏輯+1 ......但那麼誰低估了這個問題? –

+0

@TimBiegeleisen謝謝。 – Dhiraj

+0

@TimBiegeleisen我低估了你的答案。對不起,先生不向你提供理由。希望這個答案滿足你爲什麼我downvoted你的答案 – Dhiraj