我正在开发一个Java 2类的项目,该项目必须显示用户输入的一段时间内有机体的人口增长。我能够使用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;
答案 0 :(得分:0)
通过showPopulation(totalDays, organ, dailyIncrease)
调用以下函数。在此,我假设totalDays
是整个天数,organ
是&#34; organ&#34;的初始值,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
)。
答案 1 :(得分:0)
虽然我猜这是家庭作业,但这是它应该如何运作
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;
}
}
我没有运行它,所以要小心进一步的错误。
您忘记了终止条件。它必须总是更接近这个条件,通常是减少直到达到0或类似。
答案 2 :(得分: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);
您是否需要在每一步中打印增长?
答案 3 :(得分: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);
}
}