[C++]利用逆波兰式,简单实现下加减乘除的混合运算

来源:互联网 发布:linux命令行创建进程 编辑:程序博客网 时间:2024/05/02 01:05

测试代码

此处显示之前逆波兰式求法后的增量代码!
http://blog.csdn.net/u010989191/article/details/53135563

//简单加减乘除法运算  因为数据是放在堆栈中 所以前一个操作数是opB 后一个操作数是opAint simpleCalculate(int opA, int opB, char op) {    switch (op)    {    case '+':        return opB + opA;    case '-':        return opB - opA;    case '*':        return opB * opA;    case '/':        return opB / opA;    default:        return 0;    }}//计算表达式的值int calculate(string polish) {    stack<int> values;    bool lastIsNum = false;    for (int i = 0; i < polish.length(); i++) {        char c = polish.at(i);        if (c == ' ') {            lastIsNum = false;            continue;        }        else if (c >= '0'&&c <= '9') {            if (lastIsNum) {                int last = values.top();                values.pop();                last = last * 10 + (c - '0');                values.push(last);            }            else {                values.push(c - '0');                lastIsNum = true;            }        }        else {            lastIsNum = false;            int opA = values.top();            values.pop();            int opB = values.top();            values.pop();            int calResult = simpleCalculate(opA, opB, c);            values.push(calResult);        }    }    return values.top();}int main(){    string str;    cout << "请输入表达式: ";    cin >> str;    string result = reversePolish(str);    cout << result << endl;    int calResult = calculate(result);    cout << "计算结果: " << calResult << endl;    system("pause");    return 0;}

测试结果

这里写图片描述

0 0