-
题目描述:
-
对于一个不存在括号的表达式进行计算
-
输入:
-
存在多种数据,每组数据一行,表达式不存在空格
-
输出:
-
输出结果
-
样例输入:
-
6/2+3+3*4
-
样例输出:
-
18
-
来源:
- 2010年上海交通大学计算机研究生机试真题
-
-
#include <iostream> #include <string> #include <stack> #include <sstream> using namespace std; int level_operator(char oper) //操作符优先级 { switch(oper) { case '+': case '-': return 0; break; case '*': case '/': return 1; break; } } double count(double a, double b, char oper) //计算 { double ret; switch(oper) { case '+': ret = a + b; break; case '-': ret = a - b; break; case '*': ret = a * b; break; case '/': ret = a / b; break; default: break; } return ret; } double calculate(string strExp) { stack<double> num; stack<double> op; istringstream in(strExp, istringstream::in); double n, a, b; //operator num char oper, c; //operator while (in >> n) //每次读取一个数 { num.push(n); if (!in.eof()) //如果还有操作符,则读取一个操作符 { in >> c; if (op.empty() || level_operator(c) > level_operator(op.top())) { op.push(c); } else { do { b = num.top(); num.pop(); a = num.top(); num.pop(); oper = op.top(); op.pop(); num.push(count(a, b, oper)); }while (!op.empty() && level_operator(c) > level_operator(op.top())); op.push(c); } } } while (!op.empty()) { b = num.top(); num.pop(); a = num.top(); num.pop(); oper = op.top(); op.pop(); num.push(count(a, b, oper)); } return num.top(); } int main() { string strExp; while (cin >> strExp) { cout << calculate(strExp) << endl; } return 0; }