我正在对c编程进行分配,例如,如果用户输入,则对两个二进制数进行(+,-,*,/)操作 :“ 1001 + 1010” 必须添加两个二进制文件并给出输出“ 010011”
我的代码只能逐步获取每个输入(获取第一个二进制文件然后获取第二个二进制文件,然后选择运算符(+,-,*,/)然后生成答案),然后生成答案,但是赋值却认为要取整立即(1001 + 1010并给出答案010011)
#include <stdio.h>
int main()
{
int num, num2, binary_val, binary_val2, decimal_val = 0, decimal_val2 = 0, base = 1, rem, base2 = 1, rem2, sum;
char oprtr;
printf("Enter the first binary number(1s and 0s) \n");
scanf("%d", &num);
binary_val = num;
printf("Enter the second binary number(1s and 0s) \n");
scanf("%d", &num2);
binary_val2 = num2;
printf("choose operation +,-,/,* \n");
scanf("%char", &oprtr);
while (num > 0)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
num = num / 10;
base = base * 2;
}
while (num2 > 0)
{
rem2 = num2 % 10;
decimal_val2 = decimal_val2 + rem2 * base2;
num2 = num2 / 10;
base2 = base2 * 2;
}
if (oprtr == '+')
{
sum = decimal_val + decimal_val2;
}
else if (oprtr == '*' || oprtr == 'x' || oprtr == 'X')
{
sum = decimal_val * decimal_val2;
}
else if (oprtr == '-')
{
sum = decimal_val * decimal_val2;
}
else if (oprtr == '/')
{
sum = decimal_val / (float)decimal_val2;
}
else
{
printf("error");
}
int decimal_num, remainder, binary = 0;
while (sum > 0)
{
remainder = num % 2;
/* To count no.of 1s */
if (remainder == 1)
binary = binary + remainder * base;
sum = sum / 2;
base = base * 10;
}
printf("The Binary number of the first one is = %d \n", binary_val);
printf("The Binary number of the second one is = %d \n", binary_val2);
printf("Its decimal equivalent is = %d \n", decimal_val);
printf("Its decimal equivalent is = %d \n", decimal_val2);
printf("And their Value is = %d \n", sum);
}
答案 0 :(得分:0)
在读取运算符之前,您必须绕过第二个数字之后输入的\ n,例如getchar(); oprtr = getchar();
而不是您的scanf
您将始终打印值为0,因为您打印的是总和而不是二进制
您错过了在最后一刻之前将基数重置为1的情况
其他说明
scanf("%d%c%d", &num, &oprtr, &num2);