-4
我需要根據輸入的增加量和天數來打印一組生物體的總數。我需要將開始數量乘以增加百分比,第2天,然後第3天乘以第2天,增加百分比等。但是,我不知道如何遞歸執行此操作並按時間順序打印。我製作了這個代碼,但它沒有遵循正確的公式。我該如何修改代碼才能正確打印?以適當的時間順序遞歸打印
static void displayPopulation(double start, double increase, int day)
{
if (time == days)
{System.out.println(time + " " + (start * increase * time));}
else if(time == 1)
{System.out.println(time + " " + start); displayPopulation(start, increase, ++time);}
else
{System.out.println(time + " " + (start * increase * time));
displayPopulation(start, increase, time++);
}
}
編輯:這裏是全碼:
package populationstarter;
import java.util.*;
public class PopulationStarter {
static String Input;
static double starting;
static double increase;
static int days;
static String output;
static int time = 1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the starting number of organisms: ");
starting = scan.nextDouble();
System.out.println("Enter the % daily increase: ");
increase = scan.nextDouble() * .01 + 1;
System.out.println("Enter the # of days: ");
days= scan.nextInt();
System.out.println("Day Amount\n ------------");
displayPopulation(starting, increase, time);
}
static void displayPopulation(double start, double increase, int day)
{
if (time == days)
{System.out.println(time + " " + (start * increase * time));}
else if(time == 1)
{System.out.println(time + " " + start); displayPopulation(start, increase, ++time);}
else
{System.out.println(time + " " + (start * increase * time)); displayPopulation(start, increase, time++);}
}
}
什麼是'時間'?什麼是'天'?爲什麼'day'參數未被使用? ---請修復你的代碼格式。這是可怕的。即縮進「if」語句的內容,並在一行中放下多個語句。 – Andreas
爲什麼使用遞歸進行簡單的'for'循環可以做到的事情?如果遞歸的次數太多,遞歸會導致StackOverflowError,而'for'循環可以永久循環而不失敗。 – Andreas
對不起,天主要在主體中定義,我沒有包括,因爲我想專注於displayPopulation部分。另外,我被要求將程序分配給我的人使用遞歸。 –