我从教科书中得到以下代码来计算阶乘:
import java.math.*;
public class LargeFactorial {
public static void main(String[] args) {
System.out.println("50! is \n" + factorial(50));
} public static BigInteger factorial(long n) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
result = result.multiply(new BigInteger(i +""));
return result;
}
Run Code Online (Sandbox Code Playgroud)
但是,我真的不明白new BigInteger(i +"").为什么他们放入+""构造函数?我的意思是我们没有乘以一个空字符串,它也没有任何意义.请解释.
它只是调用BigInteger(String)构造函数,因为没有构造函数接受int.使用字符串连接是将一个讨厌的方式int为String,但它会工作.
IMO将采用更清洁的方法BigInteger.valueOf(long):
result = result.multiply(BigInteger.valueOf(i));
Run Code Online (Sandbox Code Playgroud)
(考虑到这两个问题,我会对你教科书的质量稍微保持警惕......)