简易计算器

该程序实现了一个简易的四则运算计算器,功能强大之处在于输入格式不受限制。你输入的字符串可以包含空格,也可以用括号包含优先级。

#include<iostream>
#include<stack>
#include<queue>
#include<string>
#include<map>
using namespace std;
struct node
{
    double num;
    char op;
    bool flag;
};

string str;
stack<node> s;
queue<node> q;
map<char, int> op;

void Change(){
    double num;
    node temp;
    for (int i = 0; i < str.length();) {
        if (str[i] >= '0' && str[i] <= '9') {
            temp.flag = true;
            temp.num = str[i++] - '0';
            while (i < str.length() && str[i] >= '0' && str[i] <= '9') {
                temp.num = temp.num * 10 + str[i++] - '0';
            }
            q.push(temp);
        } else if (str[i] == '('){
            temp.flag == false;
            temp.op = '(';
            s.push(temp);
        } else if (str[i] == ')'){
            while (!s.empty() && s.top().op != ')') {
                q.push(s.top());
                s.pop();
            }
            s.pop();
            i++;
        } else {
            temp.flag = false;
            while (!s.empty() && op[str[i]] <= op[s.top().op]) {
                q.push(s.top());
                s.pop();
            }
            temp.op = str[i];
            s.push(temp);
            i++;
        }
    } 
    while (!s.empty()) {
        q.push(s.top());
        s.pop();
    }
}

double Cal(){
    double temp1, temp2;
    node cur, temp;
    while (!q.empty()) {
        cur = q.front();
        q.pop();
        if (cur.flag == true) s.push(cur);
        else {
            temp2 = s.top().num;
            s.pop();
            temp1 = s.top().num;
            s.pop();
            if (cur.op == '+') temp.num = temp1 + temp2;
            else if (cur.op == '-') temp.num = temp1 - temp2;
            else if (cur.op == '*') temp.num = temp1 * temp2;
            else temp.num = temp1/ temp2;
            temp.flag == true;
            s.push(temp);
        }
    }
    return s.top().num;
}

int main() {
    op['+'] = op['-'] = 1;
    op['*'] = op['/'] = 2;
    op['('] = op[')'] = 3;
    while (getline(cin, str), str != "0") {
        for (string::iterator it = str.begin(); it != str.end(); it++) {
            if (*it == ' ') str.erase(it);
        }
        while (!s.empty()) s.pop();
        Change();
        printf("%.2f\n", Cal());
    }
    return 0;
}
posted @ 2021-02-20 18:30  snakeee  阅读(64)  评论(0)    收藏  举报