我的程序遇到一些问题,我要求用户输入起始人口,日增长率(百分比)以及他们将繁殖多少天。然后计算每天的最终人口,同时确保它们限制了用户输入的数据。我每天都得到相同的结果,而且约束也不起作用。
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句