基本上,有一群20只羊。在该群体成长为80只绵羊后,该群体不再需要受到监督。羊的数量N,每年,每年,t,见:
N = 220 /(1 + 10(0.83)^ t)
这个程序试图找出绵羊必须监督多少年,然后从零开始写出N的值,从零开始,直到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++;
}
}
}
答案 0 :(得分:2)
将数字和功率的数据类型从int更改为double。我试了一下,它运行正常。您也可能希望修改for循环以在多年时间内运行&lt; 25而不是数字&lt; 80.并将数字作为循环内的局部变量以保持清洁。
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;
}
}