我的Java程序有問題。我製作了一個程序,它接受一個整數並將其轉換爲二進制值。當數字很奇怪時,沒有任何問題。 15轉換爲1111,17轉換爲10001等等。問題出現在數字爲偶數時。如果我輸入16,18,20等,每次只返回0。此外,重要的是要注意,我通過使用遞歸方法得到我的號碼,一旦到達它的號碼就停止。奇數成功轉換爲二進制,偶數失敗
這是我的代碼。感謝我能得到的任何幫助,即使它不能解決問題。
public class binaryConverter {
static int nr = 16;
static int max = 0;
static int[] bin;
static int[] array;
static int finalBin;
public static void main(String[] args) {
maxFinder();
binMaker();
toBinary(array, 0,true);
}
//finds out how many binary numbers are used in order to decide what length to make the array,
//15 = 1111, 10000 = 16 15<16
private static void maxFinder(){
for(int i = 0, n = 1; i<nr; i++){
if(n>nr){
max = i;
break;
}
n*=2; //n doubles for every i loop, starts with one
}
}
//makes a library of standard to binary (0 = 1, 1 = 2; 2 = 4; 3 = 8...)
private static void binMaker(){
int[] temp = new int[max];
for(int i = 0; i<temp.length; i++){
if(i == 0) temp[i] = 1;
else temp[i]=2*temp[i-1];
}
bin = temp;
array = new int[bin.length];
}
//adds the array together in order to access what number the array currently resembles in binary
private static int sum(int[] ar, int length){
int sum = 0;
for(int i = 0; i<=length; i++) if(ar[i]==1) sum += bin[i];
return sum;
}
//loops until the array becomes the number in binary
private static void toBinary(int[] ar, int i, boolean one){ //i = the current number it's on, eg. 10i01, i is the third slot
if(i==array.length) return; //break if
ar[i] = (one) ? 1:0;
if(sum(ar, i)==nr){ //if the temporary array is the number but in binary ...
array = ar; //turns the static array into the temporary array
String temp = "";
for(int z = 0; z<array.length; z++) temp += array[z];
finalBin = Integer.parseInt(temp); //makes finalBin represent the original number but in binary
return;
}
else{ //else go to the next slot
toBinary(ar, i+1, true);
toBinary(ar, i+1, false);
}
}
}
編輯:我現在已經添加以下行來我的主要: 如果(finalBin = NR!)toBinary(數組,0,FALSE); System.out.println(finalBin); 這是爲了確保它可以從0開始。然而,我仍然得到了不正確的答案,因爲它給了我偶然的數字看似偶然的回報。
當您嘗試調試時發生了什麼? – shmosel
該數組變爲{1,0,0,0,0} ...,也就是說,它進行了一個完整的循環,直到它們全部變成1秒,然後變爲0 –
要計算所需的二進制位數(' maxFinder')你可以使用日誌功能,而不是...你是否必須以遞歸的方式做到這一點?有很多更聰明的解決方案:https://www.cs.indiana.edu/cgi-pub/c211/snake/ – m13r