不帶括號的表達式運算

題目:輸入行數,再在每行輸入一個表達式,得出結果。
輸入示例:
3
1+1
2.2/3
1+2*3
輸出示例:
2
0.7
7

代碼:

#include <iostream>
#include <stack>
#include <sstream>
#include <cctype>

using namespace std;

bool isNumber(char c) {
    if (isdigit(c) || c == '.') return true;
    else return false;
}

bool isOperater(char c) {
    if (c == '+' || c == '-' || c == '*' || c == '/') return true;
    else return false;
}

bool isHighLevel(char newOp, char oldOp) {
    if ((newOp == '*' || newOp == '/')
         && (oldOp == '+' || oldOp == '-' || oldOp == '#'))
        return true;
    else return false;
}

double opNumber(double a, double b, char op) {
    if (op == '+') return a + b;
    else if (op == '-') return a - b;
    else if (op == '*') return a * b;
    else if (op == '/') return a / b;
}

int main()
{
    int n;
    cin >> n;
    cin.get();
    for (int i = 0; i < n; ++i) {
        string str;
        getline(cin, str);

        str += "#";
        stack<char> sta;
        sta.push('#');
        int strLen = str.length();

        string hstr = "";
        for (int j = 0; j < strLen; ++j) {
            if (isNumber(str[j])) hstr += str[j];
            else if (isOperater(str[j])) {
                hstr += "|";
                if (isHighLevel(str[j], sta.top())) {
                    sta.push(str[j]);
                }
                else if (sta.top() == '#') {
                    sta.push(str[j]);
                }
                else {
                    hstr += sta.top();
                    sta.pop();
                    sta.push(str[j]);
                }
            }
            else if (str[j] == '#') {
                hstr += '|';
                while (!sta.empty() && sta.top() != '#') {
                    hstr += sta.top();
                    sta.pop();
                }
                break;
            }
        }

        stack<double> staNumber;
        staNumber.push(0);
        int hstrLen = hstr.length();
        stringstream ss;
        for (int j = 0; j < hstrLen; ++j) {
            if (isNumber(hstr[j])) {
                ss << hstr[j];
            }
            else if (hstr[j] == '|') {
                double temp;
                ss >> temp;
                staNumber.push(temp);
                ss.clear();
            }
            else if (isOperater(hstr[j])) {
                double a = staNumber.top();
                staNumber.pop();

                double b = staNumber.top();
                staNumber.pop();

                double c = opNumber(b, a, hstr[j]);
                staNumber.push(c);
            }
        }

        double fin = staNumber.top();
        cout << fin << endl;

    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章