中缀表达式转后缀并求值

来源:互联网 发布:商家给淘宝主播寄样品 编辑:程序博客网 时间:2024/05/17 23:33

这是个中缀表达式的求解,过程是先进行转换成后缀,然后我用的数组保存数,然后求解,我写的目前只限于单位数的中缀表达式…

#include<iostream>#include<stack>#include<string>using namespace std;int check(char buff) {    if (buff == '+' || buff == '-')return 1;    if (buff == '*' || buff == '/')return 2;    if (buff == '(')return 3;    if (buff == ')')return 4;    return 0;}bool check_(char buff) {    if (buff == '+' || buff == '-' || buff == '*' || buff == '/' || buff == '(' || buff == ')')        return true;    return false;}int main(void) {    string buff;    cin >> buff;    stack<char>st;    stack<char>num;    for (int i = 0; i<buff.length(); i++) {        if (check_(buff[i])) {//判定是否是运算符;            if (st.empty())                st.push(buff[i]);//栈为空就先将运算符压入;            else if (check(buff[i])>check(st.top())) {//当前运算符优先于栈顶运算符;                if (check(buff[i]) == 4) {                    while (st.top() != '(') {                        num.push(st.top());                        st.pop();                    }                    if (st.top() == '(') {                        st.pop();                    }                }                else {                    st.push(buff[i]);                }            }            else {//当前运算符低于栈顶运算符;                if (st.top() != '(') {                    num.push(st.top());                    st.pop();                    st.push(buff[i]);                }                else                    st.push(buff[i]);            }        }        else num.push(buff[i]);    }    while (!st.empty()) {//将剩余运算符压入num栈;        num.push(st.top());        st.pop();    }    stack<char >te;//矫正顺序,num栈是逆序    while (!num.empty()) {        cout << num.top();        te.push(num.top());        num.pop();    }    cout<<endl;    int i=0,arr[100];    while(!te.empty()){//用数组存取数字,然后求解;        if(!check_(te.top())){           arr[i++]=te.top()-'0';           te.pop();        }        else{            if (te.top() == '+'){                arr[i-2]+=arr[i-1];                i--;                te.pop();            }            else if (te.top() == '-'){                arr[i-2]-=arr[i-1];                i--;                te.pop();            }            else if (te.top()== '*'){                arr[i-2]*=arr[i-1];                i--;                te.pop();            }            else if (te.top() == '/'){                arr[i-2]/=arr[i-1];                i--;                te.pop();            }        }    }    cout<<arr[0];    return 0;}
原创粉丝点击