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和1的數字?因爲你用'nextInt()'讀取輸入。 – Maljam
對不起!是!它假設只是0或1! – ohdust
確切的問題是什麼?該程序似乎工作正常。你想擺脫前面的零並輸出只有8位數字? –