c中的二进制加法,为什么会发生运行时错误?

时间:2019-02-27 13:13:17

标签: c binary

我正在尝试编写一个代码,该代码可以将2个十进制数字0转换为1,然后将它们相加并打印2个初始数字和最终和的二进制值。它编译没有问题,但是当我运行它时,它在转换并打印num1和num2(初始数字)后立即崩溃,我似乎找不到问题。 二进制加法的一般公式为:

*和的第i位=二进制1的第i位+二进制2的第i位+进位因子(0或1)

如果sum> 1,减去2并在下一个运算中加1(这是我前面提到的进位系数)

下面是代码

#include <stdio.h>

// Converting decimal number to a binary number
void convertDecToBin(double num, int len, int binary[]) {

    // this function STORES conversion result in binary[]

    double tmp = num;
    binary[0] = 0;
    for (int i = 0; i < len; i++) {
        tmp *= 2;
        binary[i + 1] = tmp >= 1;
        if (tmp >= 1) {
            tmp -= 1;    
        }
    }

}


// Binary number addition
void addTwoBinary(int binary1[], int binary2[], int sum[]) {

    int tmp;
    int carry;

    for (unsigned int i = 20; i >= 0; i--) {
        if (i == 20 || tmp <= 1) {
            carry = 0;
        }
        else if (tmp > 1) {
            carry = 1;
        }
        sum[i] = binary1[i] + binary2[i] + carry;
        tmp = sum[i];
        if (sum[i] > 1) {
            sum[i]-=2;
        }
    }
}

//Printing the numbers
void PrintBinary(int binary[], int len) {
    for (unsigned int i = 0; i < len; i++) {
            printf("%d", binary[i]);

    }
}

int main(void) {

    double num1, num2;
    int binary1[30], binary2[30], sum[30];

    scanf("%lf", &num1);
    scanf("%lf", &num2);

    convertDecToBin(num1, 30, binary1);
    convertDecToBin(num2, 30, binary2);

    printf("num1 is ");
    PrintBinary(binary1, 21);
    printf("\nnum2 is ");
    PrintBinary(binary2, 21);

    addTwoBinary(binary1, binary2, sum);

    printf("\nsum is ");
    PrintBinary(sum, 21);

    return 0;
}

0 个答案:

没有答案