在Java循环中更新Total

时间:2014-01-28 17:40:03

标签: java loops for-loop

我无法在每次循环运行时更新总数。 我一直在使用值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);
    }

}

}

3 个答案:

答案 0 :(得分:2)

您只能获得计算一次的第一个原因!

您应该阅读用户的输入并在循环中计算:

while(daysMultiply != -1){ // when the user wants to quit he'll enter -1, for example
    daysMultiply = keyboard.nextInt();
    dailyTotal = 0;
    dailyTotal2 = 0;
    for (int i = 1; i<=daysMultiply; i++)
    {
        dailyTotal = startingOrganisms*dailyPopulation*.01;
        dailyTotal2 = startingOrganisms + dailyTotal;
        System.out.println("Population for day " + i + " = " + dailyTotal2);
    }
}

答案 1 :(得分:1)

根据您的逻辑,结果看起来您希望在循环for循环时更改startingOrganisms值。

根据您的输入值为:2, 50 and 5且结果为:3, 4.5, 6.75, 10.125, 15.1875粗略猜测将为startingOrganisms分配值{ {1}}

首次更改将更改dailyTotal2的数据类型。

startingOrganisms

接下来是在for循环中更改其值:

double startingOrganisms;

或者更好,将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);
        }

答案 2 :(得分:0)

每天根据原始人口计算,而不是根据当前人口计算。尝试调整计算以使用当前人口乘以增长因子:

growth = dailyTotal*dailyPopulation*.01;
dailyTotal dailyTotal + growth;

或一行

dailyTotal = dailyTotal + (dailyTotal*dailyPopulation*.01);