簡體   English   中英

Double/ Long 到 BigInteger

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM