需要使用初学者逻辑创建C++二进制计算器

Need to create C++ Binary Calculator using beginner logic

本文关键字:创建 C++ 二进制 计算器 初学者      更新时间:2023-10-16

我已经成功地设置了如何使用以下代码完成二进制加法,

#include <stdio.h>
#include <iostream>
using namespace std;
int main() {    
    long a, b;
    int i = 0, r = 0, sum[20];
    cout << "Enter the first binary number: ";
    cin >> a;
    cout << "Enter the second binary number: ";
    cin >> b;
    while (a != 0 || b != 0)
    {
        sum[i++] = (a % 10 + b % 10 + r) % 2;
        r = (a % 10 + b % 10 + r) / 2;
        a = a / 10;
        b = b / 10;
    }
    if (r != 0)
        sum[i++] = r;
    --i;
    cout << "The sum of the two binary numbers is: ";
    while (i >= 0)
        cout << sum[i--];
    cout << ". ";
    system("pause");
    return 0;
}

我需要使用类似的方法来允许二进制减法和乘法。我尝试了以下代码,但它没有按计划工作。添加 if 语句(如 if c=1)会导致循环继续多次,永远不会给出正确的答案。单独使用减法公式,给我的结果与加法相同。有人可以帮我解决这个问题吗?谢谢

#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
    long a, b;
    int c = 0;
    cout << "Enter the first binary number: ";
    cin >> a;
    cout << "Enter the second binary number: ";
    cin >> b;
    cout << "Which operation do you want to complete: Add=1, Subtract=2, Multiply=3: ";
    cin >> c;
    if (c = 1){
        while (a != 0 || b != 0)
        {
            int i = 0, r = 0, sum[20];
            sum[i++] = (a % 10 + b % 10 + r) % 2;
            r = (a % 10 + b % 10 + r) / 2;
            a = a / 10;
            b = b / 10;
        }
        if (r != 0)
            sum[i++] = r;
        --i;
        cout << "The sum of the two binary numbers is: ";
        while (i >= 0)
            cout << sum[i--];
        cout << ". ";
    }
    if (c = 2) {
        while (a != 0 || b != 0)
        {
            int i = 0, r = 0, sub[20];
            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 << "The difference of the two binary numbers is: ";
            while (i >= 0)
                cout << sub[i--];
            cout << ". ";
        }
    if (c = 3) {
        while (a != 0 || b != 0)
        {
            int i = 0, r = 0, prod[20];
            prod[i++] = (a % 10 * b % 10 + r) % 2;
            r = (a % 10 * b % 10 + r) / 2;
            a = a / 10;
            b = b / 10;
            if (r != 0)
                prod[i++] = r;
            --i;
            cout << "The product of the two binary numbers is: ";
            while (i >= 0)
                cout << prod[i--];
            cout << ". ";
        }
    }
}

这会将 1 分配给c

if (c = 1){

相比之下c比 1。

if (c == 1){

请为您的编译器打开警告。 你会被告知这样的错别字。