我正在为我的Java类编写一个程序,该程序以给定的开始年份(2011)计算一年的人口,并以每年1.2%的速度增加人口. 2011年的人口为7.000(我使用的是小数,而不是十亿).我目前有此代码.
int startYear = 2011;
int endYear = user_input.nextInt();
double t = 1.2; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
DecimalFormat nf = new DecimalFormat("2");
System.out.println("Population in " + endYear + ": " (nf.format(pEnd)));
代码中没有错误,一切正常,但是我在使用pEnd公式时遇到了麻烦.目前,当我输入2016年作为结束年度时,我得到22824.我尝试使用谷歌搜索公式,但找不到任何东西.你们中的任何一个都对公式有想法吗?如果输入2016作为结束年度,则应该在7.433左右
解决方法:
使用Math.pow(1 t / 100,nbr)代替Math.exp(nbr * t),因为您需要(1 t / 100)^ nbr(即,将1 t / 100乘以nbr倍),而不是exp ^( nbr * t):
double pEnd = pStart * Math.pow(1 + t / 100, nbr); // Ending population of user input
标签:eclipse,java,math
来源: https://codeday.me/bug/20191118/2025473.html