-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部分。另外,我被要求将程序分配给我的人使用递归。 –