计算后缀表达式
2010-09-27 19:48
183 查看
#include <cstdlib> #include <iostream> #include <assert.h> #include <cmath> #include <stack> #include <cctype> #include <string> using namespace std; /*利用栈计算后缀表达式:(1)、运算数是单数字的非负整数 (2)、处理的二元整数运算符为:+、-、*、/、%、^ */ //后缀表达式类 class postfixEval { public: postfixEval(){} string getPostfixEval();//返回后缀表达式 void setPostfixEval(const string & postfixExp);//设置后缀表达式 int evaluate();//计算后缀表达式 private: string postfixExpression;//要计算的后缀表达式 stack<int> operandStack;//运算数栈 void getOperands(int &left, int &right);//获取左右两个操作数 int compute(int left, int right, char oper) const; //计算left oper right bool isOperator(char ch) const;//ch是+、-、*、/、%、^中的一个 }; string postfixEval::getPostfixEval() { return postfixExpression; } void postfixEval::setPostfixEval(const string & postfixExp) { postfixExpression = postfixExp; } bool postfixEval::isOperator(char ch) const { if ((ch == '+') || (ch == '-') || (ch == '*') || (ch == '/') || (ch == '%') || (ch == '^')) return true; else return false; } void postfixEval::getOperands(int &left, int &right) { if(operandStack.empty()) throw "操作符太多"; else { left = operandStack.top(); operandStack.pop(); } if(operandStack.empty()) throw "操作符太多"; else { right = operandStack.top(); operandStack.pop(); } } int postfixEval::compute(int left, int right, char oper) const { int result; switch (oper) { case '+': result = left + right; break; case '-': result = left - right; break; case '*': result = left * right; break; case '/': if (right == 0) { throw "除数不能为0!"; } else result = left / right; break; case '%': if (right == 0) { throw "除数不能为0!"; } else result = left % right; break; case '^': if ((left == 0) || (right == 0)) { throw "操作数不能为0!"; } else result = pow(right, left); break; } return result; } int postfixEval::evaluate() { int i; int left, right; for (i=0; i<postfixExpression.length(); i++) { char c = postfixExpression[i]; if (isdigit(c)) { operandStack.push(c - '0'); } else if (isOperator(c)) { getOperands(left, right); operandStack.push(compute(left, right, c)); } else if(!isspace(c)) { // throw "错误的操作符!"; } } int result = operandStack.top(); operandStack.pop(); if (!operandStack.empty()) { throw "操作数太多!"; } else { return result; } } int main() { string str; getline(cin, str); postfixEval exp; exp.setPostfixEval(str); try { cout<<"计算结果为:"<<exp.evaluate()<<endl; } catch (const char *e) { cout<<"异常为:"<<e<<endl; } }
相关文章推荐
- 栈的应用--表达式计算&中缀转后缀
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- 中缀表达式转化为后缀表达式,计算中缀表达式,计算后缀表达式(有注释)(逆波兰表达式)
- 表达式计算3 +-*/^() 数据没有负数 后缀表达式
- 【转】算术表达式中缀形式转后缀形式,并基于后缀式和栈进行计算
- 【数据结构】用栈实现的简单计算器(先转换为后缀表达式、可以计算带括号的)
- 堆栈实现,计算后缀表达式
- 关于java 的科学计算算法(前,中,后缀表达式的转换)——计算器制作的心得
- 中缀表达式与后缀表达式的转化与计算
- C++实现计算器功能(包括计算含未知量的式子),输出后缀表达式
- 中缀转后缀表达式||后缀表达书计算
- 中缀表达式转后缀表达式并计算
- 二叉树 计算后缀表达式
- 前缀表达式、后缀表达式和中缀表达式的计算(double型)
- 【数据结构】用栈实现对后缀表达式的计算
- 中缀表达式转换为后缀表达式 简易实现(c++)(简易表达式计算)
- 中缀表达式转换成后缀表达式,进行简单表达式的计算
- c++中缀表达式转后缀表达式并计算
- 蓝桥杯 算法训练 表达式的计算(中缀转后缀表达式求值)
- 数据结构栈之计算后缀表达式