我在每次循环运行时都无法更新总数。
我一直在使用值2、50和5来检查我的工作。
总数应为:3、4.5、6.75、10.125和15.1875,但我所能得到的只是第一个总数。
很感谢任何形式的帮助!谢谢!!
这是我的代码:
import java.util.Scanner;
public class Population
{
public static void main(String[] args)
{
int startingOrganisms;
int dailyPopulation;
int daysMultiply;
double dailyTotal = 0;
double dailyTotal2 = 0;
double dailyTotal3 = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Starting # of Organisms:");
startingOrganisms = keyboard.nextInt();
System.out.println("Daily Population Increase(%):");
dailyPopulation = keyboard.nextInt();
System.out.println("# of Days They'll Multiply:");
daysMultiply = keyboard.nextInt();
for (int i = 1; i<=daysMultiply; i++)
{
dailyTotal = startingOrganisms*dailyPopulation*.01;
dailyTotal2 = startingOrganisms + dailyTotal;
System.out.println("Population for day " + i + " = " + dailyTotal2);
}
}
}
最佳答案
根据您的逻辑和结果,看起来您想在遍历for循环时更改startingOrganisms
值。
给定您的输入值为:2, 50 and 5
,结果为:3, 4.5, 6.75, 10.125, 15.1875
,应该将startingOrganisms
的粗略猜测设为dailyTotal2
第一个更改将更改startingOrganisms
的数据类型。
double startingOrganisms;
接下来是在for循环中更改其值:
for (int i = 1; i <= daysMultiply; i++) {
dailyTotal = startingOrganisms * dailyPopulation * .01;
dailyTotal2 = startingOrganisms + dailyTotal;
startingOrganisms = dailyTotal2;
System.out.println("Population for day " + i + " = " + dailyTotal2);
}
或者更好的方法是将
startingOrganisms
当作您的dailyTotal2
计数器,该计数器保存更新后的值并递增:for (int i = 1; i <= daysMultiply; i++) {
dailyTotal = startingOrganisms * dailyPopulation * .01;
startingOrganisms = startingOrganisms + dailyTotal;
//startingOrganisms = dailyTotal2
System.out.println("Population for day " + i + " = " + startingOrganisms);
}
您在上述两种情况下得到的结果都是您所期望的:
Starting # of Organisms:
2
Daily Population Increase(%):
50
# of Days They'll Multiply:
5
Population for day 1 = 3.0
Population for day 2 = 4.5
Population for day 3 = 6.75
Population for day 4 = 10.125
Population for day 5 = 15.1875