我的程序遇到了一些问题,我要求用户输入开始人口,每日增长百分比以及他们将增加的天数。然后计算每天的最终总体数,同时确保它们是用户输入数据的约束。我每天都会收到相同的结果,而且约束也没有完成他们的工作。
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);
}
}
}
}
答案 0 :(得分:0)
你的行
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;
答案 1 :(得分:0)
我认为你需要在你的循环中设置一个:
startPopulation = endPopulation;
然后你再做一次循环迭代。
试试这个例子
endPopulation=(startPopulation*increase)+startPopulation;
startPopulation = endPopulation;
如果您不想丢失startPopulation的初始值, 只是将它存储在某个地方,然后再改变它(我建议的方式)。