我在这里做错了什么(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]);
            }
        }
    }

附言我知道还有其他方法可以做到这一点,所以请不要建议使用其他方法。

您的代码中存在一些问题:

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 (z!=0)    
    {
           x=z%2;     
           a[j]=x;
           j++;
           z=z/2;
    }

最新更新