我的程序遇到一些问题,我要求用户输入起始人口,日增长率(百分数)以及他们将繁殖多少天。然后计算每天的最终人口,同时确保它们限制了用户输入的数据。我每天都得到相同的结果,并且约束也不起作用。

input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
for (int days=0;days<=daysofIncrease+1;days++)
{

  if (startPopulation>=2 || increase >0 || daysofIncrease>=1)
  {
         endPopulation=(startPopulation*increase)+startPopulation;
         JOptionPane.showMessageDialog(null,"This is the organisms end population: "+endPopulation+" for day: "+days);
  }

      else
        {
          input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
          startPopulation=Double.parseDouble(input);
          input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
          increase=Float.parseFloat(input);
          input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
          daysofIncrease=Double.parseDouble(input);

      }
      }
      }
    }

最佳答案

你的线

endPopulation=(startPopulation*increase)+startPopulation;


无法正确计算最终人口。您根本没有使用daysofIncrease。

我认为您需要一遍又一遍。请注意,我尚未对此进行测试,可能需要进行调整,但是它应该可以为您提供帮助:

double interimPopulation = startPopulation;
for (int days=1; days<=daysofIncrease; days++) {
   interimPopulation *= (1.0 + (increase/100.0));  //get next day's population
}
endPopulation = interimPopulation;

关于java - 人口随时间变化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19364290/

10-11 10:54