1

我的程序有一些问题,我要求用户输入起始人口、每日增长百分比以及他们将成倍增长的天数。然后计算每天的最终人口,同时确保它们是用户输入数据的约束。我每天都得到相同的结果,而且约束也没有发挥作用。

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);

      }
      }
      }
    }
4

2 回答 2

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;
于 2013-10-14T16:05:35.610 回答
0

我认为您需要在循环中的某个位置设置: startPopulation = endPopulation; 然后您对循环进行另一次迭代。试试这个例如

endPopulation=(startPopulation*increase)+startPopulation;

startPopulation = endPopulation;

如果您不想丢失 startPopulation 的初始值,只需将其存储在某处,然后再更改它(我建议的方式)。

于 2013-10-14T16:05:52.363 回答