2017-06-04 263 views
0

我想從二進制數字使用BigInteger類打印十進制數。 我使用BigInteger類的BigInteger(String val,int radix)構造函數將給定的二進制值轉換爲十進制值,但它正在打印在構造函數中傳遞的確切二進制值.Waht是錯誤嗎? 的代碼如下:如何使用BigInteger將二進制轉換爲十進制?

System.out.print("Ente the decimal number:"); 
s=String.valueOf(sc.nextInt()); 

BigInteger i=new BigInteger(s,10); 
System.out.println(i); 
+0

如果您嘗試將二進制轉換爲十進制,則可以使用'new BigInteger(s,2)'。如果你試圖將十進制轉換爲二進制,你應該編輯這個問題。 –

+0

爲什麼?你爲什麼不使用'BigDecimal'? – EJP

回答

0

如果你試圖解析輸入字符串作爲二進制,你應該寫:

BigInteger i=new BigInteger(s,2); 

當你打印

System.out.println(i); 

它將默認顯示爲十進制。

但是,將數字讀取爲int然後轉換爲String並傳遞給BigInteger構造函數是沒有意義的,因爲這限制了可以工作的數字範圍。

嘗試:

s = sc.nextLine(); 
BigInteger i=new BigInteger(s,2); 
System.out.println(i); 
1

其實不打印二進制數的十進制值

要打印該值是String val

準確的十進制表示根據你把radix在本聲明中,它將採取如下行動:

BigInteger i = new BigInteger("11101", 10); // 11101 

11101這個輸出實際上是十進制數不是一個二進制數

爲了獲得預期的結果,你應該radix值更改爲2後,它將打印二進制數的十進制值:

BigInteger i = new BigInteger("11101", 2); 
System.out.println(i); 

輸出

29 
0

爲了解析二進制輸入,使用Scanner.nextBigInteger()以2爲基數:

System.out.print("Enter the decimal number:"); 
BigInteger i = sc.nextBigInteger(2); 
System.out.println(i); 

默認情況下輸出爲十進制。

相關問題