2014-09-25 31 views
0

我正在開發一個Java 2類的項目,該項目必須在用戶輸入的天數內顯示有機體的種羣增長。我能夠使用while循環實現該方法,但難以將其轉換爲遞歸方法。使用遞歸方法而不是while循環

while(day <= totalDays) 
{ 
    if (day == 1){ 
     System.out.println(organs); 
     day++; //day one there is no increase 
    } 
    else{ 
     organs = organs + organs*(increase/100); //add % increase of organisms 
     System.out.println(organs); 
     day++;} 
} 

這是我迄今爲止遞歸方法的嘗試失敗。

public static double showPopulation(int dayNum, int days, double organisms, 
     double dailyIncrease) 
{ 
    if(dayNum == totalDays) 
    { 
     return organisms + (organisms*dailyIncrease); 
    } 
    else 
     return showPopulation(dayNum+1, days, organisms, dailyIncrease) + organisms*dailyIncrease; 
+6

爲什麼你需要遞歸,如果你有一個完全有效的迭代求解? – NPE 2014-09-25 17:14:47

+2

遞歸在兩種情況下是有意義的:何時它確實有助於使代碼變得更短,更清晰或者任務本身具有遞歸性質。 – Andrey 2014-09-25 17:16:48

+0

...或者當你在Erlang工作,沒有任何選擇:) – Pointy 2014-09-25 17:22:14

回答

0
public int population(int days, int startingOrganisms, double dailyIncrease) { 
     if (days <= 1) { 
     System.out.print(days + " " + startingOrganisms); 
     //no increase, finish condition 
     return startingOrganisms; 
     } else { 
     // we need to find the population of yesterday to know how much organisms exist today 
     int populationYesterday = population(days - 1, startingOrganisms, dailyIncrease); 
     int populationToday = populationYesterday + (populationYesterday * dailyIncrease/100); 

     System.out.print(days + " " + populationToday); 
     return populationToday; 
     } 
    } 

然後就是調用它,並打印出結果

System.out.println(population(10, 1000, 30.2); 

你需要打印每一個成長的每一步?

+0

是的,我現在試圖補充說。需要以日數/人口的形式。 – Kurter21 2014-09-25 18:44:55

+0

@ Kurter21我添加了一些印花,可以幫助您實現 – Claudio 2014-09-25 19:42:48

0

通過showPopulation(totalDays, organ, dailyIncrease)調用以下函數。這裏我假設totalDays是整個天數,organ是「器官」的初始值,而dailyIncrease是一個百分比。

public static double showPopulation(int dayNum, double organ, double dailyIncrease) { 
    if(dayNum <= 1) { 
     return organ; 
    } else { 
     return (1 + dailyIncrease) * showPopulation(dayNum - 1, organ, dailyIncrease); 
    } 
} 

通常,當使用迭代時,我們通常從基本情況開始。就這個問題而言,這意味着第1天,或者當dayNum == 1。而當應用遞歸時,我們通常從程序的最終狀態開始考慮問題。在這個問題中,這意味着最後一天(totalDays)。

0

雖然我猜作業THISIS,這裏是它如何工作

public static double showPopulation(int dayNum, double organisms, 
     double dailyIncrease) 
{ 
    if(dayNum == 1) 
    { 
     return organisms + (organisms*dailyIncrease); 
    }else{ 
     return showPopulation(dayNum-1, organisms, dailyIncrease) + organisms*dailyIncrease; 
    } 
} 

我沒有跑,所以進一步的bug提防。

您忘記了終止條件。它必須總是更接近這個條件,通常減少到0或相似。

0

試試這個代碼:

public static double showPopulation(int totalDay,int days, double organisms, 
      double dailyIncrease) { 
     if(days == totalDay) { 
      return organisms; 
     } 
     else{ 
      organisms+=organisms*dailyIncrease; 
      return showPopulation(totalDay,++days, organisms, dailyIncrease); 
     } 

    }