我正在制定一個程序,計算一年中給定的開始年(2011年)的人口數量,每年增加1.2%的人口。 2011年的人口是7.000(我使用的是小數,而不是數十億)。這裏是我的代碼試圖讓一段時間循環正常工作
package src;
import java.util.Scanner;
import java.text.DecimalFormat;
public class Demographics {
public static void main(String[] args) {
Scanner user_input= new Scanner(System.in);
//Part 1
System.out.println("===--- Part 1 ---===");
System.out.println("Population in 2011: 7.000");
System.out.print("What is the desired year? (> 2011) ");
int startYear = 2011;
int endYear = user_input.nextInt();
while (endYear <= startYear){
System.out.println("Invalid end year.");
System.out.print("What is the desired year? (> 2011) ");
endYear = user_input.nextInt();
break;
}
double t = 0.012;
double nbr = (endYear - startYear);
double pStart = 7.000;
double pEnd = pStart * Math.exp(nbr * t);
DecimalFormat nf = new DecimalFormat("#.000");
System.out.println("Population in " + endYear + ":(nf.format(pEnd)));
//Part 2
System.out.println("===--- Part 2 ---===");
System.out.print("What is the target population? (> 7.000) ");
double pTarget = user_input.nextDouble();
while (pTarget <= pStart){
System.out.println("Invalid target population.");
System.out.print("What is the target population? (> 7.000) ");
pTarget = user_input.nextDouble();
break;
}
while (pStart < pTarget){
startYear++;
pStart = pStart + (pStart * 0.012);
System.out.println("Population in " + startYear + ": " + nf.format((pStart)));
}
}
}
部分的我的代碼1計算,當用戶進入其每年的人口工作的一部分,則第2部分展示了多少年,當用戶輸入一個將採取的計算人口達到這一點。
這裏是行不通
//Part 3
System.out.println("===--- Part 3 ---===");
t = 1.2;
pStart = 7.000;
pEnd = pStart * Math.exp(nbr * t);
while (pStart < pTarget){
startYear++;
pEnd = pStart + (pStart * 0.012);
if (pEnd >= pStart * 2){
System.out.println("Population in " + startYear + ": " + nf.format((pEnd)) + " Population growth rate " + ": " + (t/2));
}else{
System.out.println("Population in " + startYear + ": " + nf.format((pEnd)) + " Population growth rate " + ": " + t);
}
}
目前,當我在我的代碼它的無限循環,而不人口乘以有3部分的代碼。我在第3部分中要做的與第2部分中的內容大致相同,但在第3部分中,它將顯示人口增長率(t),並在人口翻倍時將其除以2。例如:
2019年的人口:7.705;人口增長率:1.2%
2020年人口:7.798;人口增長率:1.2%
2021年人口:7.892;人口增長率:1.2%
...
人口六八年:13.873;人口增長率:1.2%
2069年人口:14.040;人口增長率:0.6%
任何人有任何想法如何實現這一目標?
呃,除非我讀錯了,否則你永遠不會在你的循環中改變pStart。那麼如何滿足循環退出條件呢? – OldProgrammer
我會在循環中更改pStart? –
也許沒什麼。這很可能意味着你的循環條件沒有意義。逐行檢查您的代碼。 – OldProgrammer