#include<string>
#include<stack>
#include <iostream>
#include<cmath>
using namespace std;
const int N = 6;
pair<char, int>priority[N];
void set_pair() {
priority[0] = make_pair(')', 0);
priority[1] = make_pair('(', 0);
priority[2] = make_pair('+', 1);
priority[3] = make_pair('-', 1);
priority[4] = make_pair('*', 2);
priority[5] = make_pair('/', 2);
}
int find(char ch) {
for (int i = 0; i < N; i++) {
if (priority[i].first == ch) {
return priority[i].second;
}
}
}
string prefix() {
string str, ans;
stack<char>sign;
int cnt = 0;
cin >> str;
reverse(&str[0], &str[0] + str.size());
for (int i = 0; i < str.size(); i++) {
if (isdigit(str[i]) == 0) {
if (str[i] == '(') {
while (sign.top() != ')' && !sign.empty()) {
ans += sign.top();
sign.pop();
}
if (sign.top() == ')') {
sign.pop();
}
}
else if (str[i] == ')') {
sign.push(str[i]);
}
else {
while (!sign.empty() && find(sign.top()) > find(str[i])) {
ans += sign.top();
sign.pop();
}
sign.push(str[i]);
}
}
else {
string s;
while (isdigit(str[i]) != 0||str[i]=='.') {
s += str[i];
i++;
}
ans += s;
ans += " ";
i--;
}
}
while (!sign.empty()) {
ans += sign.top();
sign.pop();
}
reverse(&ans[0], &ans[0] + ans.size());
cout << ans;
return ans;
}
double calnum(string str, int i) {
double n = 0, p;
int cnt = 0;
bool b = 0;
while (i >= 0 && (isdigit(str[i]) != 0 || str[i] == '.')) {
if (str[i] == '.') {
i--;
b = 1;
continue;
}
if (b == 0) {
cnt++;
}
i--;
}
i++;
p = pow(10, cnt - 1) * 1.0;
while(isdigit(str[i]) != 0 || str[i] == '.'){
if (str[i] == '.') {
i++;
continue;
}
n += (str[i] - '0') * p;
p /= 10;
i++;
}
return n;
}
double calculat(string str) {
stack<double>num;
for (int i = str.size() - 1; i >= 0; i--) {
if (isdigit(str[i]) == 0) {
double n;
switch (str[i]) {
case '+':n = num.top(); num.pop(); n += num.top(); break;
case '-':n = num.top(); num.pop(); n -= num.top(); break;
case '*':n = num.top(); num.pop(); n *= num.top(); break;
case '/':n = num.top(); num.pop(); n /= num.top(); break;
default:continue;
}
num.pop();
num.push(n);
}
else {
double n = calnum(str, i);
num.push(n);
while (i >= 0 && (isdigit(str[i]) != 0 || str[i] == '.')) {
i--;
}
}
}
return num.top();
}
int main() {
set_pair();
while (1) {
string s = prefix();
cout << "\n" << calculat(s) << "\n\n";
}
return 0;
}
献上拙作,欢迎指正。