您的位置:首页 > 其它

计算后缀表达式

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: