设计程序实现二进制数字的加减乘除,输入一串字符,包含两个参与运算的操作数,一个加减乘除运算符,中间以空格隔开,然后根据运算符进行运算输出运算结果(二进制)
如:输入:101 110 +
输出:1011
输入:101 110 *
输出:11110(高位为0可不输出)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int BinaryToDec(char ch[],int n)
{
int sum,flag,i;
sum = 0;
flag = 1;
for(i=n-1; i>=0; i--)
{
sum += flag * (ch[i]-'0');
flag *= 2;
}
return sum;
}
void getResult(int a,int b,char op)
{
char ch[100];
int result;
switch (op)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default :
return ;
}
itoa(result,ch,2);
printf("%s\n",ch);
}
int main()
{
char ch1[100],ch2[100],oper;
int num1,num2;
while(scanf("%s %s %c",ch1,ch2,&oper) != EOF)
{
num1 = BinaryToDec(ch1,strlen(ch1));
num2 = BinaryToDec(ch2,strlen(ch2));
getResult(num1,num2,oper);
}
return 0;
}