代码实现
#include <iostream>
#include <stack>
#include <string>
#include <iomanip>
using namespace std;
double cal(double num1, double num2, char op)
{
if (op == '+')
{
return num1 + num2;
}
else if (op == '-')
{
return num1 - num2;
}
else if (op == '*')
{
return num1 * num2;
}
else if (op == '/')
{
return num1 / num2;
}
else
{
throw runtime_error("illegal operation");
}
}
void cal_process(stack<double> &num, stack<char> &op)
{
double num1 = num.top();
num.pop();
double num2 = num.top();
num.pop();
char cur_op = op.top();
op.pop();
num.push(cal(num2, num1, cur_op));
}
double cal_exp(const string &exp)
{
stack<char> op;
stack<double> num;
for (size_t i = 0; i < exp.size();)
{
if (isdigit(exp[i]))
{
double tmp_val = 0.0;
while (i < exp.size() && isdigit(exp[i]))
{
tmp_val = tmp_val * 10 + exp[i] - '0';
++i;
}
num.push(tmp_val);
}
else
{
if (exp[i] == ')')
{
while (!op.empty() && op.top() != '(')
{
cal_process(num, op);
}
op.pop();
}
else if (exp[i] == '+' || exp[i] == '-')
{
while (!op.empty() && (op.top() == '*' || op.top() == '/' || op.top() == '+' || op.top() == '-'))
{
cal_process(num, op);
}
op.push(exp[i]);
}
else if (exp[i] == '(' || exp[i] == '*' || exp[i] == '/')
{
while (!op.empty() && (op.top() == '*' || op.top() == '/'))
{
cal_process(num, op);
}
op.push(exp[i]);
}
++i;
}
}
while (num.size() > 1 && !op.empty())
{
cal_process(num, op);
}
return num.top();
}
int main(int argc, char const *argv[])
{
ios::sync_with_stdio(false);
std::string s;
while (getline(cin, s) && s != "0")
{
cout << fixed << setprecision(2) << cal_exp(s) << endl;
}
return 0;
}