📄 d_postfixeval.cpp
字号:
#include "d_postfixEval.h"
void postfixEval::getOperands(double& left, double& right)
{
if (operandStack.empty())
throw expression_error("postfixEval: 太多操作数");
right = operandStack.top();
operandStack.pop();
if (operandStack.empty())
throw expression_error("postfixEval: 太多运算符");
left = operandStack.top();
operandStack.pop();
}
double postfixEval::compute(double left, double right, char command) const
{
double value;
switch(command)
{
case '+': value = left + right;
break;
case '-': value = left - right;
break;
case '*': value = left * right;
break;
case '/': if (right == 0)
throw
expression_error("postfixEval: 除数不能为0");
value = left / right;
}
return value;
}
bool postfixEval::isCommand(char command) const
{
return command == '+' || command == '-' || command == '*' || command== '/';
}
postfixEval::postfixEval()
{}
string postfixEval::getPostfix() const
{
return postfixExpression;
}
void postfixEval::setPostfix(const string& postfix)
{
postfixExpression = postfix;
while(!operandStack.empty())
operandStack.pop();
}
double postfixEval::evaluate()
{
double left, right, expValue;
char ch;
for (unsigned int i=0; i < postfixExpression.length(); i++)
{
ch = postfixExpression[i];
if (isdigit(ch))
operandStack.push(ch - '0');
else if (isCommand(ch))
{
getOperands(left, right);
operandStack.push(compute(left, right, ch));
}
else if(!isspace(ch))
throw expression_error("postfixEval: 非法的算式");
}
expValue = operandStack.top();
operandStack.pop();
if (!operandStack.empty())
throw expression_error("postfixEval: 非法的算式");
return expValue;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -