华科14_2
来源:互联网 发布:硅谷ios程序员 编辑:程序博客网 时间:2024/06/05 09:25
问题:
以二进制方式输入两个正整数,然后再输入一个四则运算符号,按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 1000using 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进制数ansint 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
- 华科14_2
- 华科16_2
- 华科15_2
- 第七章 14_泛型_2
- 2010_2
- 3_2
- IOCP _2
- 4_2
- 3_2
- 11_2
- 8583_2
- 指来指去_2
- 作业_2
- 工作总结_2
- 集合_2
- 基础_2
- 三分_2
- 贪心_2
- JS学习(6)----Math And Random
- MySQL 数据类型
- Orika简单使用
- Jsp页面通过href拼接url向后台传中文乱码问题
- 成为更好开发者的几点建议
- 华科14_2
- JSTL
- 不同编译器对于(a++)*(a++)和(a++)*(++a)和(++a)*(a++)和(++a)*(++a)的运算结果
- [牛客网]错题整理(2)
- java设计模式之单例模式的七种写法
- HDU 3001 Travelling (状态压缩DP +TSP问题)
- win下安装composer
- php模拟登陆
- 虚幻4环境交互【草地扰动】