我的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