逆波兰计算器
#include<bits/stdc++.h> #define INF 0x3f3f3f3f3f3f3f3f #define mod 1000000007 #define IOS ios::sync_with_stdio(false) #define endl '\n' using namespace std; typedef long long ll; const int maxn = 1e5 + 10; stack<double>stk; int main() { IOS; double a, b; char c, str[10]; int i = 0; scanf("%c", &c); while (c != '#') { while (isdigit(c) || c == '.') { str[i++] = c; str[i] = '\0'; scanf("%c", &c); if (c == ' ') { a = atof(str); stk.push(a); i = 0; break; } } switch (c) { case '+': { a = stk.top(); stk.pop(); b = stk.top(); stk.pop(); stk.push(a + b); break; } case'-': { a = stk.top(); stk.pop(); b = stk.top(); stk.pop(); stk.push(b - a); break; } case'*': { a = stk.top(); stk.pop(); b = stk.top(); stk.pop(); stk.push(a * b); break; } case'/': { a = stk.top(); stk.pop(); b = stk.top(); stk.pop(); if (a == 0) { printf("Error!除数不能为0"); return -1; } stk.push(b / a); break; } } scanf("%c", &c); } printf("%llf", stk.top()); return 0; }
输入
1 2 3 - 4 * + 10 5 / + # (以#为结束符)
输出
-1.000000
中缀表达式—>后缀表达式
#include<bits/stdc++.h> #define INF 0x3f3f3f3f3f3f3f3f #define mod 1000000007 #define IOS ios::sync_with_stdio(false) #define endl '\n' using namespace std; typedef long long ll; const int maxn = 1e5 + 10; stack<char>s; string ss; int getnum(int& i,bool negtive) { int ans = 0; while (ss[i]>='0' && ss[i]<='9') { ans = ans * 10 + ss[i] - '0'; ++i; } if (negtive)ans = -ans; return ans; } int main() { char c; char temp; getline(cin, ss); int i; for (i = 0;i < ss.size();++i) { while (isdigit(ss[i])) { printf("%c", ss[i]); ++i; if (ss[i]<'0' || ss[i]>'9') { printf(" "); break; } } if (ss[i] == ')') { do { temp = s.top(); s.pop(); if (temp != '(')printf("%c ", temp); } while (temp != '('); } else if (ss[i] == '+' || ss[i] == '-') { if (s.empty())s.push(ss[i]); else { do { temp = s.top(); s.pop(); if (temp == '(')s.push(temp); else { printf("%c ", temp); } } while (!s.empty() && temp != '('); s.push(ss[i]); } } else if (ss[i] == '*' || ss[i] == '/' || ss[i] == '(')s.push(ss[i]); } while (!s.empty()) { temp = s.top(); s.pop(); printf("%c ", temp); } return 0; }
输入
1+(2-3)*4+10/5
输出
1 2 3 - 4 * + 10 5 / +