第一章第十一题(人口估算)(Population projection)
- *1.11(人口估算)美国人口调查局基于以下假设进行人口估算:
- 每7秒有一个人诞生
- 每13秒有一个人死亡
- 每45秒有一个移民迁入
编写一个程序,显示未来5年的每年人口数。假设当前的人口是312 032 486,每年有365天。提示:Java中,两个整数相除,结果还是整数,小数部分被去掉。例如,5/4等于1(而不是1.25),10/4等于2(而不是2.5)。如果想得到有小数部分的精确结果,进行除法运算的两个值之一必须是一个具有小数点的数值。例如,5.0/4等于1.25,10/4.0等于2.5。
- *1.11 (Population projection) The U.S. Census Bureau projects population based on the following assumptions:
- One birth every 7 seconds
- One death every 13 seconds
- One new immigrant every 45 seconds
Write a program to display the population for each of the next five years. Assume that the current population is 312,032,486, and one year has 365 days. Hint: In Java, if two integers perform division, the result is an integer. The fractional part is truncated. For example, 5 / 4 is 1 (not 1.25) and 10 / 4 is 2 (not 2.5). To get an accurate result with the fractional part, one of the values involved in the division must be a number with a decimal point. For example, 5.0 / 4 is 1.25 and 10 / 4.0 is 2.5.
- 参考代码:
package chapter01;
public class Code_11 {
public static void main(String[] args) {
final double BORN_NUMBER = 1.0 / 7; // Births per second
final double DEAD_NUMBER = 1.0 / 13; // Deaths per second
final double IMMIGRANT_NUMBER = 1.0 / 45; // Number of immigrants per second
final int SECONDS_IN_A_YEAR = 365 * 24 * 60 * 60; // Seconds in a year
int PopulationNumberNow = 312_032_486;
int FirstYearPopulation =(int)(PopulationNumberNow + SECONDS_IN_A_YEAR * BORN_NUMBER - SECONDS_IN_A_YEAR * DEAD_NUMBER + SECONDS_IN_A_YEAR * IMMIGRANT_NUMBER);
int SecondYearPopulation = (int)(FirstYearPopulation + SECONDS_IN_A_YEAR * BORN_NUMBER - SECONDS_IN_A_YEAR * DEAD_NUMBER + SECONDS_IN_A_YEAR * IMMIGRANT_NUMBER);;
int ThirdYearPopulation = (int)(SecondYearPopulation + SECONDS_IN_A_YEAR * BORN_NUMBER - SECONDS_IN_A_YEAR * DEAD_NUMBER + SECONDS_IN_A_YEAR * IMMIGRANT_NUMBER);;
int FourthYearPopulation = (int)(ThirdYearPopulation + SECONDS_IN_A_YEAR * BORN_NUMBER - SECONDS_IN_A_YEAR * DEAD_NUMBER + SECONDS_IN_A_YEAR * IMMIGRANT_NUMBER);;
int FifthYearPopulation = (int)(FourthYearPopulation + SECONDS_IN_A_YEAR * BORN_NUMBER - SECONDS_IN_A_YEAR * DEAD_NUMBER + SECONDS_IN_A_YEAR * IMMIGRANT_NUMBER);;
System.out.println("The population number of USA in first year : " + FirstYearPopulation);
System.out.println("The population number of USA in second year : " + SecondYearPopulation);
System.out.println("The population number of USA in third year : " + ThirdYearPopulation);
System.out.println("The population number of USA in fourth year : " + FourthYearPopulation);
System.out.println("The population number of USA in fifth year : " + FifthYearPopulation);
}
}
- 结果显示:
The population number of USA in first year : 314812582
The population number of USA in second year : 317592678
The population number of USA in third year : 320372774
The population number of USA in fourth year : 323152870
The population number of USA in fifth year : 325932966
Process finished with exit code 0