华科14_2

问题:

以二进制方式输入两个正整数,然后再输入一个四则运算符号,按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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值