首页 > 解决方案 > 二进制计算器减法

问题描述

我目前正在为我的学校做一个关于二进制数的项目。我已经制作了一个可以正常工作的加法计算器,现在我正在尝试制作一个用于减法的计算器。我面临一些问题。最大的一个是我得到负数作为输出,当我使用时我binary 2's complement没有得到任何负结果,但它们仍然是错误的。示例:当110010用 (30) 减去 (50) 时,11110我的输出10-1-100不是10100. 在第二补码中转换 30 时,(00010)我的输出是110000十进制的 48

这是代码:

#include <iostream>
using namespace std;
int main() {
    long a, b;
    int i = 0, r = 0, sub[20];
    cout << "1st number: ";
    cin >> a;
    cout << "2nd number: ";
    cin >> b;
    while (a != 0 || b != 0)
    {
        sub[i++] = (a % 10 - b % 10 + r) % 2;
        r = (a % 10 - b % 10 + r) / 2;
        a = a / 10;
        b = b / 10;
    }
    if (r != 0)
        sub[i++] = r;
    --i;
    cout << "Difference: ";
    while (i >= 0)
        cout << sub[i--];
    cout << ". ";


    system("pause");
    return 0;
}

提前致谢

标签: c++binarycalculatorsubtraction

解决方案


关于减法,我可以看到您只是在逐位比较数字,如果第一个数字中的一个0位是,第二个数字中的相应位是1,它就可以了0 - 1 = -1,而不考虑其他数字的数量。

添加一个在当前数字为负数时更改其他数字的条件应该可以解决问题:

#include <iostream>
using namespace std;

int main() {
    long a, b;
    int i = 0, r = 0, sub[20];
    cout << "1st number: ";
    cin >> a;
    cout << "2nd number: ";
    cin >> b;
    while (a != 0 || b != 0)
    {
        sub[i] = (a % 10 - b % 10 + r) % 2; //Change the "i++" and put "i".
        r = (a % 10 - b % 10 + r) / 2;
        //Add this:
        while(sub[i - 1] < 0)
        {
            sub[i-1] += 2;
            sub[i]--;
        }
        //Until here
        a = a / 10;
        b = b / 10;
        i++; //Increment "i" here.
    }
    if (r != 0)
        sub[i++] = r;
    --i;
    //Add this if you want to ignore the leading 0's:
    while (i >= 1 && sub[i] == 0)
        i--;
    //Until here.
    cout << "Difference: ";
    while (i >= 0)
        cout << sub[i--];
    cout << ". ";


    system("pause");
    return 0;
}

关于在第二补码中转换数字。输入应该是怎样的?


推荐阅读