问题:
以二进制方式输入两个正整数,然后再输入一个四则运算符号,按short类型计算,并将结果按二进制输入。
分析:
自己写二进制的四则运算觉得比较麻烦,干脆通过十进制,先将要计算的数转换为10进制,然后进行相应计算,然后将结果再转换为二进制进行输出。
代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <algorithm>
#include <iomanip>
#define MAX 1000
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Binary{
char num[MAX];
void init(char *str){
strcpy(num,str);
}
void init(int x){
//用10进制数x 初始化二进制数
int size=0;
while(x != 0) {
num[size++] = (x%2) + '0';
x/=2;
}
num[size++] = '\0';
}
int toTen()const{
//将二进制数b 转化为10进制数ans
int ans=0;
int c=1;
int length = strlen(num);
for(int i=length-1;i>=0;i--){
ans+=(num[i]-'0')*c;
c*=2;
}
return ans;
}
Binary operator *(const Binary &b)const{
int m=this->toTen();
int n=b.toTen();
Binary ans;
ans.init(m*n);
return ans;
}
Binary operator /(const Binary &b)const{
int m=this->toTen();
int n=b.toTen();
Binary ans;
ans.init(m/n);
return ans;
}
Binary operator +(const Binary &b)const{
int m=this->toTen();
int n=b.toTen();
Binary ans;
ans.init(m+n);
return ans;
}
Binary operator -(const Binary &b)const{
int m=this->toTen();
int n=b.toTen();
Binary ans;
ans.init(m-n);
return ans;
}
void display(){
int length = strlen(num);
for(int i=length-1;i>=0;i--){
printf("%c",num[i]);
}
printf("\n");
}
};
int main(int argc, char** argv) {
char num1[MAX],num2[MAX];
char op;
while(scanf("%s %s %c",num1,num2,&op)!=EOF){
Binary a,b;
a.init(num1);
b.init(num2);
if(op == '+'){
Binary c= a+b;
c.display();
}else if(op == '-'){
Binary c= a-b;
c.display();
}else if(op == '*'){
Binary c= a*b;
c.display();
}else if(op == '/'){
Binary c= a/b;
c.display();
}
}
return 0;
}