//https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d?tpId=37&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=&judgeStatus=&tags=&title=54&gioEnter=menu #include <iostream> #include <vector> #include <algorithm> using namespace std; char clist[7][7] = { {'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'<', '<', '<', '<', '<', '=', '.'}, {'.', '.', '.', '.', '.', '.', '.'}, {'<', '<', '<', '<', '<', '.', '.'}, }; //二维数组列表初始化时需要注意逗号的使用,以及全局变量需要加';' string s = "+-*/()#"; char precede(char oldc, char newc){ int i = s.find(oldc); int j = s.find(newc); return clist[i][j]; } int computer(int n, char op, int m){ switch(op){ case '+': return m+n; case '-': return m-n; case '*': return m*n; case '/': return m/n; } return 0; //只有switch的函数中需要加return } int main() { string str; while(cin >> str){ str+='#'; vector<char> opt; vector<int> opn; int i = 0; opt.push_back('#'); while((opt.back()!='#')||(str[i]!='#')){ int tem = i; if(str[i]=='-'&&(i==0||str[i-1]=='(')) tem++; while(isdigit(str[tem])) //数字有正负 tem++; //cout << tem << i << "!" << endl; if(tem!=i){ opn.push_back(stoi(str.substr(i, tem-i))); i = tem; continue; } else switch(precede(opt.back(), str[i])){ case '<' : opt.push_back(str[i]); break; case '=' : opt.pop_back(); break; case '>' : int n = opn.back(); opn.pop_back(); int m = opn.back(); opn.pop_back(); opn.push_back(computer(n, opt.back(), m)); //需注意出栈顺序 opt.pop_back(); i--; //若进行比较,则不读入字符 break; } i++; // for(const char &c:opt) // cout << c; // cout << endl; // // for(const int &c:opn) // cout << c; // cout << endl; } cout << opn.back() << endl; } }