我有一个后缀表达式,我需要评估它也检查它的有效性。可以有一种方法,我首先评估表达式,如果它是有效的,那么我去计算但是这涉及做两次相同的工作。如何在一次通话中完成?
我的代码位于该函数用于评估的位置下方,我想返回写入的错误
//返回错误
任何帮助如何继续这个?
#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
int isOperand(char s){
if(s >= '0' && s<= '9')
return 1;
return 0;
}
int applyOperation(int val1, int val2, char expression){
switch(expression){
case '+':
return val2+val1;
case '-':
return val2-val1;
case '*':
return val2*val1;
case '/':
return val2/val1;
}
}
int evaluatePostfix(char* exp){
stack<int> operandStack;
int l = strlen(exp);
for(int i=0;i<l;i++){
if(isOperand(exp[i]))
operandStack.push(exp[i]-'0');
else{
if(operandStack.empty())
//return error
int val1 = operandStack.top();
operandStack.pop();
if(operandStack.empty())
//return error
int val2 = operandStack.top();
operandStack.pop();
int result = applyOperation(val1,val2,exp[i]);
operandStack.push(result);
}
}
int topElem = operandStack.top();
operandStack.pop();
if(!operandStack.empty())
//return error
return operandStack.top();
}
int main()
{
char exp[] = "231*+9-";
printf ("Value of %s is %d", exp, evaluatePostfix(exp));
return 0;
}