蓝桥杯 小计算器

#include <iostream>
#include <math.h>
#include <list>
#include <string>
#include <sstream>
using namespace std;
int sys = 10;
long long num = 0;
string op = "";
void clear() {
    num = 0;
    op = "";
}
void calcul(long long num2) {
    if (op == "ADD") {
        num = num + num2;
    }else if (op == "SUB") {
        num = num - num2;
    }else if (op == "MUL") {
        num = num*num2;
    }else if (op == "DIV") {
        if (num2 != 0) {
            num = num/num2;
        }else {
            num = -1;
        }
    }else if (op == "MOD") {
        num = num%num2;
    }else {
        //非运算操作的num指令后面的数为第一个操作数
        num = num2;
    }
}

long long change(string s) {
    long long sum = 0;
    long len = s.length();
    for (int i=0; i<len; i++) {
        char c = s[i];
        int high = 0;//高位的值
        if (isdigit(c)) {
            high = c-'0';
        }else {
            high = 10+c-'A';
        }
        sum *= sys;
        sum += high;
    }
    return sum;
}

void result() {
    long long temp = num;
    list<char> result;
    if (temp == 0) {
        result.push_front('0');
    }
    while (temp) {
        int res = temp%sys;
        if (res >= 10) {
            result.push_front('A' + res-10);
        }else {
            result.push_front('0' + res);
        }
        temp = temp/sys;
    }
    for (list<char>::iterator it = result.begin(); it!=result.end(); it++) {
        cout << *it;
    }
    cout << endl;
}

void explain(string cmd, string par) {
    if (cmd == "NUM") {
        calcul(change(par));
    }else if (cmd == "CHANGE") {
        stringstream stream(par);
        stream >> sys;
    }else if (cmd == "EQUAL") {
        result();
    }else if (cmd == "CLEAR") {
        clear();
    }else {
        op = cmd;
    }
}

int main(int argc, const char * argv[]) {
    int n;
    cin >> n;
    cin.get();
    string cmd;
    for (int i=0; i<n; i++) {
        getline(cin, cmd);
        long position = cmd.find(" ");
        if (position == -1) {
            explain(cmd, "");
        }else {
            explain(cmd.substr(0, position), cmd.substr(position+1));
        }
    }
    
    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值