我在做什么错在这里(Java)的十进制转换为二进制

这是我写的代码: 例如,我在做什么错在这里(Java)的十进制转换为二进制

1.) Input =12 

2.) No. of Digits = 2

3.) 00 (this is it: Expected Result 1100)

它打印出一半的二进制文件,但我真的不知道在哪里其他一半去。

import java.util.Scanner; 

class Decimal_to_Binary

{

public static void main(String args[])

{

Scanner Prakhar=new Scanner(System.in);

System.out.println("Enter a Number");

int x=Prakhar.nextInt();

int z=x;

int n=(int)Math.floor(Math.log10(x) +1);

System.out.println("No. of Digits="+n);

int a[]=new int[n];

int b=0;

int j=0;

while (x!=0)

{

x=z%2;

a[j]=x;

j++;

z=z/2;

}

int l=a.length;

for(int i=0;i<l;i++)

{

System.out.print(a[i]);

}

}

}

P.S.我知道还有其他方法可以做到,所以请不要使用其他方法。

回答:

有代码中的几个问题:

1)数字以二进制的方式数量(n)的计算方法(它应该是小区(Math.log2(号))由于Math.log2是在Java中不可用我们计算Math.log10(数字)/ Math.log10(2)

2)条件检查while(x!= 0)它应该是while(z!= 0)在每个循环中减少2个

3)反向打印列表打印正确的二进制表示。

下面是更正后的代码:您正在使用内部While循环是错误的

public static void main(String args[]) 

{

Scanner Prakhar=new Scanner(System.in);

System.out.println("Enter a Number");

int x=Prakhar.nextInt();

int z=x;

// correct logic for computing number of digits

int n=(int)Math.ceil(Math.log10(x)/Math.log10(2));

System.out.println("No. of Digits="+n);

int a[]=new int[n];

int b=0;

int j=0;

while (z!=0) // check if z != 0

{

x=z%2;

System.out.println(x);

a[j]=x;

j++;

z=z/2;

}

int l=a.length;

//reverse print for printing correct binary number

for(int i=l-1;i>=0;--i)

{

System.out.print(a[i]);

}

}

回答:

实际上,循环检查条件。

while (x!=0)  

{

x=z%2; --> Here x is 0 in case of even number and 1 in case of odd

a[j]=x;

j++;

z=z/2;

}

这里x是偶数的情况下,0和1在奇数的情况下(参见内部While循环第一行) 所以在您的示例的情况下,使用12,所以对于第一和第二迭代中的x是计算为0,所以这将打印和第二次迭代后x变成1,所以当循环中断。

使用以下While条件 -

while (z!=0)  

{

x=z%2;

a[j]=x;

j++;

z=z/2;

}

以上是 我在做什么错在这里(Java)的十进制转换为二进制 的全部内容, 来源链接: utcz.com/qa/258917.html

回到顶部