gpt4 book ai didi

java - 编码错误导致死循环

转载 作者:行者123 更新时间:2023-11-29 07:11:57 26 4
gpt4 key购买 nike

我正在尝试编写一个程序,它获取人口的出生率和死亡率,并循环计算年人口,直到它达到 0 或翻倍。

我的问题是它不断循环无穷无尽的难以辨认的数字,我无法修复它。

import java.util.Scanner;
public class Hwk6 {
public static void main (String[] args) {
int currentYear, currentPopulation;
double birthRate, deathRate;
Scanner stdin = new Scanner(System.in);

System.out.println("\nPopulation Estimator\n");
System.out.println("Enter Year");
currentYear = stdin.nextInt();
System.out.println("Enter Current Population");
currentPopulation = stdin.nextInt();
System.out.println("Enter Birthrate of Population");
birthRate = stdin.nextDouble();
System.out.println("Enter Deathrate of Population");
deathRate = stdin.nextDouble();

int counter = currentPopulation;
System.out.println("Population: ");
while (currentPopulation != -1)
while (counter < currentPopulation * 2) {
System.out.print(counter + " ");
counter = counter + (int)(counter * birthRate - counter * deathRate);
}
System.exit(0);
}
}

最佳答案

while 循环的某处更新 currentPopulation 的值,否则 while (currentPopulation != -1)总是 计算结果为真(除非 -1 是原始值),您将陷入无限循环。

或者你的意思是

if (currentPopulation != -1)

代替

while (currentPopulation != -1)

关于java - 编码错误导致死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13095476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com