2

我正在尝试在我的程序中添加二进制数,但我对我所拥有的不满意,我的代码添加了这样的二进制数

1010
+1111

但我想更改它,以便当我输入像 100010001 这样的二进制数时,它应该像这样添加 1010 +1111 我的代码会自动添加,因为两个数组和数组中的值我想从键盘输入二进制数它应该像上面的例子一样这是我的代码

int main()
{
    int a[4];
    int b[4];
    int carry=0;
    int result[5];


    a[0]=1;
    a[1]=0;
    a[2]=0;
    a[3]=1;

    b[0]=1;
    b[1]=1;
    b[2]=1;
    b[3]=1;

    for(int i=0; i<4; i++)
    {

        if(a[i]+b[i]+carry==3)
        {
        result[i]=1;
        carry=1;
        }
        if(a[i]+b[i]+carry==2)
        {
        result[i]=0;
        carry=1;
        }
        if(a[i]+b[i]+carry==1)
        {
        result[i]=1;
        carry=0;
        }
        if(a[i]+b[i]+carry==0)
        {
        result[i]=0;
        carry=0;
        }


    }
    result[4]=carry;
    for(int j=4; j>=0; j--)
    {
        cout<<result[j];

    }
    cout<<endl;

        return 0;
}

我是新手这么多如果有错误请纠正我并给我你最好的建议提前谢谢

4

2 回答 2

0

我看到的第一件事是你没有从最右边开始。二进制数的加法与实际的以 10 为底的数字相同,因为您从右侧开始并向左侧工作,无论您剩下多少位,都将其附加到总和的开头。

所以你的:

9 + 15

1001 + 1111

i = 3 --> [][][][0] -->进位 = 1

i = 2 --->[][][0][0] --->进位 = 1

i = 1 --->[][0][0][0] --->进位 = 1

i = 0 --->[1][0][0][0] --->进位 = 1

哦,不,我们用完了空间

所以将进位附加到总和的前面:

[1][1][0][0][0] ---> 24

于 2013-02-20T07:06:51.117 回答
0

Well, it is a pretty trivial problem.

How to add two binary numbers in c++. what is the logic of it.

For adding two binary numbers, a and b. You can use the following equations to do so.

sum = a xor b

carry = ab

This is the equation for a Half Adder.

Now to implement this, you may need to understand how a Full Adder works.

sum = a xor b xor c

carry = ab+bc+ca

Since you store your binary numbers in int array, you might want to understand bitwise operation. You can use ^ for XOR,| operator for OR, & operator for AND.

Here is a sample code to calculate the sum.

for(i = 0; i < 8 ; i++) {

sum[i] = ((a[i] ^ b[i]) ^ c); // c is carry

c = ((a[i] & b[i]) | (a[i] &c)) | (b[i] & c);

}

于 2013-02-20T07:45:49.873 回答