花了三个小时,还是太差了 #include<iostream> #include<cstdio> #include<stack> #include<map> #include<string> using namespace std; map<char, int> priority = { {'+',1},{'-',1}, {'*',2},{'/',2} }; float getnum(int &index, string str) { //将字符串化为整数 float res = 0; while (str[index] >= '0' && str[index] <= '9') { res = res * 10 + str[index++] - '0'; } return res; } float res(float a, float b, char c) { if (c == '+') return a + b; else if (c == '-') return a - b; else if (c == '*') return a * b; else return a / b; } int main() { string str; while (getline(cin , str)) { stack<float> num; stack<char> oper; //分别标识数字栈和符号栈 for (int i = 0; i < str.size(); i++) { if (str[i] >= '0' && str[i] <= '9') { num.push(getnum(i, str)); } if (str[i] == '+' || str[i] == '-'||str[i] == '*'||str[i] == '/') { if (!oper.empty()) { if(priority[oper.top()] >= priority[str[i]]) { while(priority[oper.top()] >= priority[str[i]] ) { //将优先级高的全部弹出 char c = oper.top(); oper.pop(); //弹出符号 float b = num.top(); num.pop(); //弹出数字a float a = num.top(); num.pop(); //弹出数字b num.push(res(a, b, c)); if (oper.empty()) break; } oper.push(str[i]); } else oper.push(str[i]); } else oper.push(str[i]); } } while (!oper.empty()) { char c = oper.top(); oper.pop(); //弹出符号 float b = num.top(); num.pop(); //弹出数字a float a = num.top(); num.pop(); //弹出数字b num.push(res(a, b, c)); } printf("%.2f\n", num.top()); } }