gpt4 book ai didi

java - Java 中的 for 循环 - 指数

转载 作者:行者123 更新时间:2023-12-02 06:17:15 28 4
gpt4 key购买 nike

基本上,有20只羊为一组。当羊群发展到80只羊后,就不再需要有人看管了。每年 t 的羊数量 N 可以通过以下公式找到:

N = 220/(1 + 10(0.83)^t)

该程序试图找出羊需要被监管多少年,并写出 t 的 N 值,从 0 开始,一直到 25。

这是我到目前为止的代码...它似乎不起作用,我知道与乘以幂的部分有关。我尝试使用变量“power”,在循环的每次迭代中乘以 0.83。感谢任何帮助,谢谢。

   public static void main(String[] args) {

System.out.println("A breeding group of 20 bighorn sheep is released in a protected area in Colorado.");
System.out.println("After the group has reached a size of 80 sheep, the group does not need to be supervised anymore.");
System.out.println("This program calculates how many years the sheep have to be supervised.");
int number = 20;
int power = 1;
for(int years = 0; number < 80; power*= 0.83) {
number = 220 / (1 + 10 * power);
System.out.println("After " + years + " years, the number of sheep is: " + number);
years++;
}
}
}

最佳答案

将数字和幂的数据类型从 int 更改为 double。我尝试了一下,运行正确。您可能还需要修改 for 循环,使其在 Years < 25 时运行,而不是 number < 80。并让 number 成为循环内的局部变量以保持整洁。

public static void main(String[] args) {
System.out.println("A breeding group of 20 bighorn sheep is released in a protected area in Colorado.");
System.out.println("After the group has reached a size of 80 sheep, the group does not need to be supervised anymore.");
System.out.println("This program calculates how many years the sheep have to be supervised.");
double power = 1;
boolean foundFirstOverEighty = false;
for (int years = 0; years < 25; years++) {
double number = 220 / (1 + 10 * power);
System.out.println("After " + years + " years, the number of sheep is: " + number);

if (!foundFirstOverEighty && number >= 80) {
System.out.println("First time number of sheep exceeded eighty. " + years + " years. number of sheep is: " + number);
foundFirstOverEighty = true;
}

power *= 0.83;
}
}

关于java - Java 中的 for 循环 - 指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21342800/

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