C ++中的4位二进制加法

时间:2014-12-06 02:07:16

标签: c++ binary

我们得到了一个赋值,它创建一个程序,它接受两个十进制数作为输入,并在后台执行二进制加法,然后输出一个十进制和。尽管我认为我的代码逻辑是正确的,但我似乎得到了错误的结果。

我目前的总和给了我0.正确答案应该是24。

#include <iostream>
#include <sstream>
#include <string>


using namespace std;
int add(int, int);
int decbin(int);
int bindec(long);
int binADD(string, string);

int main()
{
    int a = 15;
    int b = 9;
    int z;
    z = add(a,b);
    cout << z;
    return 0;
}


int add(int a, int b)
{
    int z;
    ostringstream x, y;
    x << decbin(a);
    y << decbin(b);
    z = binADD(x.str(), y.str());
    return z;
}

int decbin(int x)
{
    int d[16];
    int i = 0;
    int j;
    int ans;


    while(x > 0)
    {
        d[i] = x % 2;
        i++;
        x = x / 2;
    }

    for(j = i - 1; j >= 0; j--)
    {
       ans = d[j];

    }

     return ans;
}

int bindec(int x)
{
    int bin, dec = 0, rem, base = 1;

    bin = x;
    while (x > 0)
    {
       rem = x % 10;
       dec = dec + rem * base;
       base = base * 2;
       x = x / 10;
    }

    return dec;
}

int binADD(string a, string b)
{
   int carry = 0;
   int result[5];
   int res;
   int ans;


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

    if(a[i] == '1' && b[i] == '1' && carry == 0)
    {
        result[i] = 0;
        carry = 1;
    }
    else if(a[i] == '0' && b[i] == '1' && carry == 1)
    {
        result[i] = 0;
        carry = 1;
    }
    else if(a[i] == '1' && b[i] == '1' && carry == 1)
    {
        result[i] = 1;
        carry = 1;
    }
    else if(a[i] == '1' && b[i] == '0' && carry == 1)
    {
        result[i] = 0;
        carry = 1;
    }
    else if(a[i] == '1' && b[i] == '0' && carry == 0)
    {
        result[i] = 1;
        carry = 0;
    }
    else if(a[i] == '0' && b[i] == '0' && carry == 1)
    {
        result[i] = 1;
        carry = 0;
    }
    else if(a[i] == '0' && b[i] == '1' && carry == 0)
    {
        result[i] = 1;
        carry = 0;
    }
    else if(a[i] == '0' && b[i] == '0' && carry == 0)
    {
        result[i] = 0;
        carry = 0;
    }

}

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

ans = bindec(res);
return ans;

}

0 个答案:

没有答案