#include <iostream> #include <string> #include <vector> #include <algorithm> #include <stack> #include <map> using namespace std; map<char, int> mymap = { {'+', 0},{'-', 0},{'/', 1},{'*', 1} }; float jisusan(float x, float y, char oper){ float res; switch(oper){ case '+': res = x + y; break; case '-': res = x - y; break; case '*': res = x * y; break; case '/': res = x / y; break; } return res; } int main() { stack<float> numStack; stack<char> operStack; //operator 运算符 string expr; //expression 表达式 while(getline(cin, expr)){ for(int i = 0; i < expr.size(); i++){ if(expr[i] >= '0' && expr[i] <= '9'){ //表明这是一个数字 可能有很多位 int j = i; while(j < expr.size() && expr[j] >= '0' && expr[j] <= '9'){ j++; continue; } //此时j越界,或者j是操作符 i 到 j - 1为数字 float num = 0; while(i != j){ num *= 10; num += (expr[i] - '0'); i++; } i--; numStack.push(num); }else{ //运算符先跟栈里的比较 //此次的运算符是一定要放进去的 while(!operStack.empty() && mymap[operStack.top()] >= mymap[expr[i]]){ //栈顶的优先级 >= 当前的优先级 //弹出两个数和操作符计算结果然后放到numstack float a1 = numStack.top(); numStack.pop(); float a2 = numStack.top(); numStack.pop(); char c = operStack.top(); operStack.pop(); float res = jisusan(a2, a1, c); numStack.push(res); } operStack.push(expr[i]); } } //把剩余的都弄出来 while(!operStack.empty()){ float a1 = numStack.top(); numStack.pop(); float a2 = numStack.top(); numStack.pop(); char c = operStack.top(); operStack.pop(); float res = jisusan(a2, a1, c); numStack.push(res); } float a1 = numStack.top(); numStack.pop(); //printf("%f\n", a1); //这里用cout方便点 cout << a1 <<endl; } } // 64 位输出请用 printf("%lld")