java - Java 中的 for 循环 - 指数

标签 java for-loop exponentiation

基本上,有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/

相关文章:

c++ - C++17 中新的基于范围的 for 循环如何帮助 Ranges TS?

ios - Playground 执行失败 : <EXPR>:15:33: error: type 'Int' does not conform to protocol 'BooleanType'

java - 在java中重新分配其复制引用时更改原始对象

java - 聊天应用程序 - 当聊天 Activity 位于前台时如何停止推送通知?

javascript - 如何从 for 循环创建数组并在稍后使用它

performance - 影响 RSA 加密/解密时间的因素

r - 负底取幂

java - Java 中的模幂问题

java - 如何确定 Scala 中调用的 JAR 的名称?

java - JasperReports 服务器 : How to export report as html file using url