如何正确使用Math.log?

How to properly use Math.log?

所以我得到了这个公式来计算给定利息的任何金额翻倍所需的年数 (i)

log(2) / log(1 + (i/100) )

所以这是我的代码:

import java.util.Scanner;

public class JavaApplication37 {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);  
        System.out.println("What's the interest rate?: ");
        int i = reader.nextInt(); 
        double t = (Math.log(2))/(Math.log(1+(i/100)));
        System.out.println("It takes " + t + " years before the amount has doubled");
    }
}

这给了我输出:在数量翻倍之前需要 Infinity 年

我做错了什么?

问题是 100 被假定为整数。您应该将 100 写为 100.0,它会 运行。 这是因为 1.02.3 等值假定为双精度而不是浮点数。注意小数点。

所以重写你的代码如下,它会 运行:

import java.util.Scanner;

public class JavaApplication37 {




    public static void main(String[] args) {
       Scanner reader = new Scanner(System.in);  
        System.out.println("What's the interest rate?: ");
    int i = reader.nextInt(); 
    double t = (Math.log(2))/(Math.log(1+(i/100.0)));
    System.out.println("It takes " + t + " years before the amount has doubled");

    }

}