当我调用我的multi()时,它会很好地计算二进制数,但不会计算adds()。如果我按顺序切换两个,它将计算adds()而不计算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;
}
答案 0 :(得分:-1)
你的全局变量没有被初始化。在您使用的adding()
函数中:
binary1 = binary3 / 10
binary2 = binary4 / 10
在binaryproduct函数中,您有两个名为binary3的本地整数,您不能使用的二进制文件。
您应该使用唯一名称,初始化变量,在不需要全局变量的位置使用局部变量。