#include <iostream> #include <stack> using namespace std; int Priority(char ch) { switch(ch) { case '(': return 3; case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } } int main() { char opt[100] = {0}; stack<int> stack_num; //保存操作数 stack<char> stack_opt; //保存操作符 int i = 0, tmp = 0; char option; int num1, num2; cout << "Please input : " << endl; cin >> opt; while (opt[i] != '\0' || stack_opt.empty() != true) { if (opt[i] >= '0' && opt[i] <= '9') //操作数进栈 { tmp = tmp * 10 + opt[i] - '0'; i++; if (opt[i] < '0' || opt[i] > '9') { stack_num.push(tmp); tmp = 0; } } else //操作符 { if (stack_opt.empty() || (stack_opt.top() == '(' && opt[i] != ')') || Priority(opt[i]) > Priority(stack_opt.top())) //操作符进栈 { stack_opt.push(opt[i]); i++; continue; } if (stack_opt.top() == '(' && opt[i] == ')') //操作符出栈不计算 { stack_opt.pop(); i++; continue; } if ((opt[i] == '\0' && stack_opt.empty() != true) || opt[i] == ')' && stack_opt.top() != '(' || Priority(opt[i]) <= Priority(stack_opt.top())) //出栈 计算 { option = stack_opt.top(); stack_opt.pop(); switch(option) { case '+': num1 = stack_num.top(); stack_num.pop(); num2 = stack_num.top(); stack_num.pop(); stack_num.push(num1 + num2); break; case '-': num1 = stack_num.top(); stack_num.pop(); num2 = stack_num.top(); stack_num.pop(); stack_num.push(num2 - num1); break; case '*': num1 = stack_num.top(); stack_num.pop(); num2 = stack_num.top(); stack_num.pop(); stack_num.push(num1 * num2); break; case '/': num1 = stack_num.top(); stack_num.pop(); num2 = stack_num.top(); stack_num.pop(); stack_num.push(num2 / num1); break; } } } } cout << "result : " << stack_num.top() << endl; return 0; }
后缀表达式计算(代码)
猜你喜欢
转载自blog.csdn.net/cainiao000001/article/details/80209283
今日推荐
周排行