[英]Double/ Long to BigInteger
我正在尝试制作一个程序,找到 2 的大 integer 'n' 的幂。
我收到 double 无法转换为 BigInteger 的错误。 所以我想知道可以将 double/long 转换为 BigInteger 吗?
import java.math.*;
import java.util.Scanner;
public class LargePow2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("n = ?");
int n = sc.nextInt();
System.out.println("2^" + n + " is \n" + pow2(n));
}
public static BigInteger pow2(long n){
BigInteger result = BigInteger.ONE;
result = Math.pow(n, 2);
return result;
}
}
也许最好避免使用 Math.pow() function,因为它以双精度返回结果,这在非常大的数字的情况下不太准确。
public static BigInteger pow2(long n){
return BigInteger.valueOf(n).pow(2);
}
您可以将双精度转换为 BigDecimal,然后再转换为 BigInteger:
BigInteger result = BigDecimal.valueOf(Math.pow(n, 2)).toBigInteger();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.