2011-01-31 178 views
0

我想在java中創建一段代碼,它將十進制值轉換爲二進制而不使用內置二進制轉換器命令。十進制到二進制轉換器

但它不工作...

public class MainFrame { 
public static void binary(int number) { 

    String result = new String(); 

    int binaryValues[] = {1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1}; 

    if (number == 0) { 
     result = result + "0"; 
    } else if (number == 1) { 
     result = result + "1"; 
    } else { 
     for (int i = 0; i < 11; i++) { 
      while(number >= binaryValues[i]) { 
       if (number % binaryValues[i] >= 0) { 
        result = result + "1"; 
        number -= binaryValues[i]; 
       } else { 
        result = result + "0"; 
    //    number -= binaryValues[i]; 
       } 
      } 
     } 
    } 

    System.out.println(result); 
} 

public static void main(String[] args) { 
    binary(5); 
} 
} 
+2

是這個家庭作業? – Bozho 2011-01-31 09:27:17

+1

看起來像功課,你有一個代碼。請解釋你到目前爲止所瞭解的內容。 – 2011-01-31 09:29:22

+0

它不是功課,我只是對如何做它感興趣 – java 2011-01-31 09:36:24

回答

0

取下else塊這一行:

number -= binaryValues[i]; 

原因:如果數字大於2 ñ ,那麼你想添加0並且不想減去2 n

並刪除while聲明,這是沒有必要的(除非所有數字都小於2 )。只要保持for循環和if/else。

終於,if條件不是模而是負。對我來說,以下工作:

for (int i = 0; i < 11; i++) { 
    if (number - binaryValues[i] >= 0) { 
     result = result + "1"; 
     number -= binaryValues[i]; 
    } else { 
     result = result + "0"; 
    } 
} 
2

對於整數> = 0:

public class DecimalToBinary { 

    public static void main(String[] args) { 
     int dec = 127; 
     StringBuilder binary = new StringBuilder(); 
     do { 
      binary.insert(0, dec % 2); 
      dec /= 2; 
     } while (dec != 0); 
     System.out.println(binary.toString()); 
    } 
} 
0
import java.util.Scanner; 
public class BinaryConversion { 
public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
System.out.println("Enter a decimal number: "); 
    int numerator = input.nextInt(); 
     int num = numerator; 
     boolean runLoop = true; 
    String digit = ""; 
    while(runLoop){ 
     int bin = numerator % 2; 
    numerator = (numerator/2); 
    digit= bin+digit; 
    if (numerator == 0) { 
     break; 
    } 

    } 
    input.close(); 
    System.out.println("The binary value of "+num+" is "+digit); 
} 
}