#include <iostream>
#include <vector>
#include <cctype>
#include <cstdlib>
// 运算式
void calculate(float& a, float& b, char c) {
switch (c)
{
case '+':
a += b;
break;
case '-':
a -= b;
break;
case '*':
a *= b;
break;
case '/':
a /= b;
break;
}
}
// 判断运算子
bool isSymbol(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; }
using std::vector;
using std::cin, std::cout, std::endl;
int main(void) {
vector <float> numbers; // 存储结果
vector <char> OS; // operator stacking 运算子堆叠
char c; // 用于测试输入字符
float num; // 输入的数值
int bracket = 0; // 左括号数量
while ((c = cin.get()) != '\n') {
if (isdigit(c)) {
cin.unget();
cin >> num;
numbers.push_back(num);
}
else if (c == '(') {
OS.push_back(c);
bracket++;
}
else if (c == ')') {
// 异常处理,括号不匹配
try {
bracket--;
if (bracket < 0) {
throw 505;
}
}
catch (...) {
cout << "异常处理:括号不匹配!" << endl;
exit(0);
}
int N = static_cast<int> (OS.size()), M, n = 0;
for (int i = N - 1; i >= 0; i--) {
n = i;
if (OS[i] == '(') {
break;
}
else {
M = static_cast<int> (numbers.size());
calculate(numbers[M - 2], numbers[M - 1], OS[i]);
numbers.pop_back();
}
}
OS.erase(OS.begin() + n, OS.end());
}
else if (c == '+' || c == '-') { // 运算子 + 或 -
int N = static_cast<int> (OS.size()), i = -1, M; // FILO 先进后出 first in last out
for (i = N - 1; i >= 0; i--) {
if (isSymbol(OS[i])) { // 如果是运算符 + - * /
M = static_cast<int> (numbers.size());
calculate(numbers[M - 2], numbers[M - 1], OS[i]);
numbers.pop_back();
}
else {
break;
}
}
if (i > 0) {
OS.erase(OS.begin() + i, OS.end());
}
OS.push_back(c);
}
else if (c == '*' || c == '/') { // 运算子 * 或 /
int N = static_cast<int> (OS.size()), i = -1, M; // FILO 先进后出 first in last out
if (OS.back() == '*' || OS.back() == '/') {
for (i = N - 1; i >= 0; i--) {
if (isSymbol(OS[i])) { // 如果是运算符 + - * /
M = static_cast<int> (numbers.size());
calculate(numbers[M - 2], numbers[M - 1], OS[i]);
numbers.pop_back();
}
else {
break;
}
}
}
if (i > 0) {
OS.erase(OS.begin() + i, OS.end());
}
OS.push_back(c);
}
}
for (int i = static_cast<int> (OS.size()) - 1, M; i >= 0; i--) {
// 异常处理:括号不匹配 或 运算子数量和数字不均
try {
if (numbers.size() > 1 && isSymbol(OS[i])) {
M = static_cast<int> (numbers.size());
calculate(numbers[M - 2], numbers[M - 1], OS[i]);
numbers.pop_back();
}
else {
throw 505;
}
}
catch (...) {
cout << "异常处理:括号不匹配 或 运算子数量和数字不均!" << endl;
exit(0);
}
}
cout << numbers[0]; // 利用逆波兰表达式求值法获得最终答案
return 0;
}