1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| #include <stdio.h> #include <stdlib.h> #include <stack> #include <cstring> #include <iostream> #include <utility> #include <map> #include <algorithm> #include <vector> #include <climits> #include <string> #include <ctime> #include <cmath> #include <sstream> #include <queue> using namespace std;
struct node { double num; char op; bool flag; };
string str; stack<node> s; queue<node> q; map<char, int> op;
void change() { double num; node temp; for (int i = 0; i < str.length();) { if (str[i] >= '0' && str[i] <= '9') { temp.flag = true; temp.num = str[i++] - '0'; while (i < str.length() && str[i] >= '0' && str[i] <= '9') { temp.num = temp.num * 10 + (str[i] - '0'); i++; } q.push(temp); } else { temp.flag = false; while (!s.empty() && op[str[i]] <= op[s.top().op]) { q.push(s.top()); s.pop(); } temp.op = str[i]; s.push(temp); i++; } } while (!s.empty()) { q.push(s.top()); s.pop(); } }
double cal() { double temp1, temp2; node cur, temp; while (!q.empty()) { cur = q.front(); q.pop(); if (cur.flag == true) { s.push(cur); } else { temp1 = s.top().num; s.pop(); temp2 = s.top().num; s.pop(); temp.flag = true; if (cur.op == '+') temp.num = temp2 + temp1; else if (cur.op == '-') temp.num = temp2 - temp1; else if (cur.op == '*') temp.num = temp2 * temp1; else temp.num = temp2 / temp1; s.push(temp); } } return s.top().num; }
int main() { op['+'] = op['-'] = 1; op['*'] = op['/'] = 2; while (getline(cin, str), str != "0") { for (string::iterator it = str.end(); it != str.begin(); it--) { if (*it == ' ') str.erase(it); } while (!s.empty()) s.pop(); change(); printf("%.2f\n", cal()); } system("pause"); return 0; }
|