2017-02-02 141 views
-1
/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package binary_to_decaimal; 


import java.util.*; 
public class Binary_to_Decaimal { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     // TODO code application logic here 
     int n,dec=0,i=0,N=0; 
     Scanner in=new Scanner(System.in); 
     System.out.println("Enter number in binary form like 0 1 or 1 0"); 
     n=in.nextInt(); 
     while(n > 0) 

     { 
      dec = n % 10; 
      N =N+ dec *(int)Math.pow(2,i); 
      i++; 
      n=n/10; 
     } 
     System.out.println("Decimal \t"+N); 
    } 
} 

如何在二進制程序爲11(3)時運行程序以上並獲取所需的十進制數?如何幹運行程序代碼'二進制到十進制'

+4

你是什麼意思的「試運行」在這裏做? – Maroun

+1

你的問題真的不清楚。請嘗試再次解釋你想達到的目標。 – Guy

+1

使轉換成爲一種方法並編寫測試? – Fildor

回答

0

可能是這將幫助你:

public int getDecimalFromBinary(int binary){ 

    int decimal = 0; 
    int power = 0; 
    while(true){ 
     if(binary == 0){ 
      break; 
     } else { 
      int tmp = binary%10; 
      decimal += tmp*Math.pow(2, power); 
      binary = binary/10; 
      power++; 
     } 
    } 
    return decimal; 
} 
+0

空運行意味着手動測試Java代碼。 –

+0

向我解釋每次迭代的概念後面的代碼行會發生什麼情況。 dec = n%10; N = N + dec *(int)Math.pow(2,i); i ++; n = n/10; –