2016-04-18 52 views
1

試圖學習Java(空閒時間)並堅持爲什麼這會輸出比我想要的更多的變量。我想它只是打印出8位。我嘗試過放入& 255,但沒有做任何事情來擺脫尾隨數字。在二進制數字中輸出比8位更多的數字

例子: 總和是:0000111110

Scanner sn = new Scanner(System.in); 
int arr[] = new int[10]; 
int i,m,n,sum,carry=0; 

    System.out.print("Enter 8-bit signed binary number:"); 
      int n1 = sn.nextInt(); 

      System.out.print("Enter another binary number:"); 
      int n2 = sn.nextInt(); 

      for(i=arr.length-1;i>=0;i--){ 
       m=n1%10; 
       n=n2%10; 
       n1=n1/10; 
       n2=n2/10; 
       sum=m+n+carry; 

       if(sum==1) 
       { 
        arr[i]=1; 
        carry=0; 
       } 

      else if(sum==2) 
       { 
        arr[i]=0; 
        carry=1; 
       } 

      else if(sum==3) 
       { 
        arr[i]=1; 
        carry=1; 
       } 

       else{ 

        arr[i]=m+n+carry&255; 
       } 

      } 
      System.out.printf("The sum is:"); 
      for(i=0;i<arr.length;i++) { 
       System.out.print(arr[i]); 
      } 
      System.out.println(""); 
     } 
+0

用戶應該輸入什麼作爲輸入,「僞二進制數」?如只有0和1的數字?因爲你用'nextInt()'讀取輸入。 – Maljam

+0

對不起!是!它假設只是0或1! – ohdust

+0

確切的問題是什麼?該程序似乎工作正常。你想擺脫前面的零並輸出只有8位數字? –

回答

0

你前導零的原因,是因爲你強制程序來計算10位,並打印10位(int arr[] = new int[10])。爲了避免計算/打印額外的位,你可以改變的條件下進行循環,並跟蹤有多少位的總和有:

Scanner sn = new Scanner(System.in); 
    int arr[] = new int[10]; 
    int m,n,sum,carry = 0, nBits = 0; //Declare nBits, number of bits the final sum has 

    System.out.print("Enter 8-bit signed binary number:"); 
    int n1 = sn.nextInt(); 

    System.out.print("Enter another binary number:"); 
    int n2 = sn.nextInt(); 

    for(int i = arr.length-1 ; (n1|n2|carry) != 0 ; i--, nBits++) { 
     m=n1%10; 
     n=n2%10; 
     n1=n1/10; 
     n2=n2/10; 
     sum=m+n+carry; 

     if(sum==1) { 
      arr[i]=1; 
      carry=0; 
     } 

     else if(sum==2) { 
      arr[i]=0; 
      carry=1; 
     } 

     else if(sum==3) { 
      arr[i]=1; 
      carry=1; 
     } 

     else { 
      arr[i]=m+n+carry&255; 
     } 

    } 
    System.out.printf("The sum is:"); 
    for(int i = arr.length-nBits ; i < arr.length ; i++) { 
     System.out.print(arr[i]); 
    } 
    System.out.println(); 
} 

條件變更爲(n1|n2|carry) != 0,換句話說,而任何的三個變量不等於零,在每個週期迭代nBits