#include <iostream> #include<stack> #include<string> using namespace std; double operation(double x, double y, char op) { //计算,注意结果有小数 double res=0; if (op == '/') res= x / y; else if (op == '*') res= x * y; else if (op == '-') res=x - y; else res= x + y; return res; } int main() { string str; stack<double>digit; //数字栈 stack<char>op; //运算栈 while (cin >> str) { int i = 0; double res = 0; while (i < str.size()) { if ('0' <= str[i] && str[i] <= '9') { //获取数字 res = (str[i] - '0') + res * 10; } else { digit.push(res); //当前数字入栈,res归0 res = 0; if (str[i] == '*' || str[i] == '/') { //若是乘除,将运算栈顶所有乘除法出栈运算 while (!op.empty() && (op.top() == '*' || op.top() == '/')) { double y = digit.top(); digit.pop(); double x = digit.top(); digit.pop(); digit.push(operation(x, y, op.top())); op.pop(); } } else { //若是加减,清空运算栈 while (!op.empty()) { double y = digit.top(); digit.pop(); double x = digit.top(); digit.pop(); digit.push(operation(x, y, op.top())); op.pop(); } } op.push(str[i]); } i++; } digit.push(res); //将余下的运算符出栈计算 while (!op.empty()) { double y = digit.top(); digit.pop(); double x = digit.top(); digit.pop(); digit.push(operation(x, y, op.top())); op.pop(); } cout<<digit.top(); } }