当我调用multi()时,它将很好地计算二进制数,但不会计算出adding()。如果我按顺序切换两个,它将计算adding(),而不计算multi()。第二个函数调用未显示其值是否有原因?它将打印printf,但不打印值。任何帮助都会很棒。

#include <stdio.h>

long binary1, binary2, binary3, binary4, multiply = 0;
int binaryproduct(int, int);
int digit, factor = 1;
int multi();
int adding();


int main()
{
    binary3 = binary1;
    binary4 = binary1;

    printf("Enter the first binary number: ");
    scanf("%ld", &binary1);

    printf("Enter the second binary number: ");
    scanf("%ld", &binary2);

    multi();
    printf("\n");
    adding();
}

int adding()
{
    int i = 0, remainder = 0, sum[20];

    while (binary3 != 0 || binary4 != 0) {
        sum[i++] =(binary3 % 10 + binary4 % 10 + remainder) % 2;
        remainder =(binary3 % 10 + binary4 % 10 + remainder) / 2;
        binary1 = binary3 / 10;
        binary2 = binary4 / 10;
    }

    if (remainder != 0) {
        sum[i++] = remainder;
    }

    --i;

    printf("Sum of two binary numbers: ");

    while (i >= 0) {
        printf("%d", sum[i--]);
    }

    return 0;
}


int multi()
{
    while (binary2 != 0) {
        digit =  binary2 % 10;
        if (digit == 1) {
            binary1 = binary1 * factor;
            multiply = binaryproduct(binary1, multiply);
        } else {
            binary1 = binary1 * factor;
        }
        binary2 = binary2 / 10;
        factor = 10;
    }

    printf("Product of two binary numbers: %ld", multiply);
    return 0;
}

int binaryproduct(int binary3, int binary4)
{
    int i = 0, remainder = 0, sum[20];
    int binaryprod = 0;

    while (binary1 != 0 || binary2 != 0) {
        sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2;
        remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2;
        binary1 = binary1 / 10;
        binary2 = binary2 / 10;
    }

    if (remainder != 0) {
        sum[i++] = remainder;
    }

    --i;

    while (i >= 0) {
        binaryprod = binaryprod * 10 + sum[i--];
    }

    return binaryprod;
}

最佳答案

您的全局变量尚未初始化。在adding()函数中,您可以使用:


  二进制1 =二进制3/10
  
  二进制2 =二进制4/10


在binaryproduct函数中,有两个不用的本地int命名为binary3,binary4。

您应该使用唯一的名称,初始化变量,在不需要全局变量的地方使用局部变量。

09-05 13:02