[英]What am I Doing Wrong Here(Java) Decimal to Binary
这是我编写的代码:例如,
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]);
}
}
}
PS我知道还有其他方法可以做到,所以请不要建议使用其他方法。
您的代码中存在一些问题:
1)计算二进制数(n)中位数的方式(应为ceil(Math.log2(number))。由于Math.log2在Java中不可用,因此我们计算Math.log10(number)/ Math.log10( 2)
2)条件检查while(x!= 0)它应该是while(z!= 0),因为您在每个循环中将z潜水2
3)反向打印列表以打印正确的二进制表示形式。
下面是更正的代码:
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循环中使用的循环检查条件是错误的。
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条件-
while (z!=0)
{
x=z%2;
a[j]=x;
j++;
z=z/2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.