簡體   English   中英

我該如何解決這個問題我想將十進制數轉換為二進制數

[英]how can i fix this i want to convert decimal number to binary

public class Binar{
public static void main(String[] args){
    int num = 7;
    long Binary = cBtD(num);
System.out.printf("%d numri decimal = %d binar" , num, Binary);
}
public static long cBtD(int num){
    long BinaryNumber = 0;
    int  i = 0;
    long reminder;
    while(num > 0){
        reminder = num % 2;
        num /= 2;
        ++i;
    }
  for (int j = i - 1; j >= 0; j--) {
        System.out.print(BinaryNumber[j]); 
  }
    return BinaryNumber;
}}

我有這個錯誤,它說“需要數組,但找到很久了”和“System.out.print(BinaryNumber[j]);”

此錯誤背后的原因是,您已將BinaryNumber變量定義為long並且它不是數組。 但是您正試圖像訪問數組一樣訪問它。 請在下面查看我修改后的答案:

public class Binar {
public static void main(String[] args) {
    int num = 7;
    String Binary = cBtD(num);
    System.out.printf("%d numri decimal = %s binar", num, Binary);
}

public static String cBtD(int num) {
    String BinaryNumber = "";
    long reminder;
    if (num == 0) {
        return "0";
    }
    while (num > 0) {
        reminder = num % 2;
        BinaryNumber = String.valueOf(reminder).concat(BinaryNumber);
        num /= 2;
    }
    return BinaryNumber;
}
}

發生該錯誤是因為您定義了 BinaryNumber 的類型 'long' 並且您想將其用作數組。

我改了一下,試試看:

public class Binar {

    public static void main(String[] args) {
        int num = 7;
        int[] binaryArray = cBtD(num);
        String numbers = "";
        for (int aBinaryArray : binaryArray)
            numbers += aBinaryArray;

        System.out.printf("%d numri decimal = %d binar" , num, Integer.parseInt(numbers));
    }

    private static int[] cBtD(int num){
        int i = 0;
        int temp[] = new int[7];
        int binaryNumber[];
        while (num > 0) {
            temp[i++] = num % 2;
            num /= 2;
        }
        binaryNumber = new int[i];
        int k = 0;
        for (int j = i - 1; j >= 0; j--) {
            binaryNumber[k++] = temp[j];
        }
        return binaryNumber;
    }
}

或者您可以簡單地使用這些方法將十進制轉換為二進制:

Integer.toBinaryString();

或這個:

Integer.toString(n,2);

所有數字本質上都是二進制的。 但是,無論您以二進制、十六進制還是八進制顯示它們都只是一個表示問題。 這意味着您想將它們打印為字符串。 即使您執行以下操作:

int v = 123;
System.out.println(v); // v is printed as a decimal string.

因此,要將它們轉換為二進制字符串,只需在除以二(通過余數運算符)后將余數添加到字符串中。

int n = 11;
String s = "";

s = (n%2) + s; // s = "1"
n/=2;  // n == 5
s = (n%2) + s; // s = "11"
n/=2   // n == 2
s = (n%2) + s; // s = "011";
n/=2   // n == 1
s = (n%2) + s; // s = "1011";
n/=2;  // n == 0

n == 0 so your done.

return s and print it.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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