尝试学习Java(空闲时间)并坚持为什么这会输出比我想要的更多的变量。我想它只打印出8位。我试过放入& 255,但没有做任何事情来摆脱拖尾数字。
实施例: 总和是: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)
你得到前导零的原因是因为你强迫程序计算10位,并打印10位(int arr[] = new int[10]
)。为了避免计算/打印额外的位,你可以改变for循环的条件,并跟踪总和有多少位:
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
。