计算表达式
题目:计算(4+5)*(7-2)
思路:本文只介绍简单处理后的表达式,来简单的阐明栈在计算表达式中的应用,例如上面的表达式,要用栈的话,需要对表达式做转换,转成4 5 + 7 2 - *,然后利用栈做计算。
int express(string input)
{
stack<int> st;
int op1,op2;
int i=0;
while(i < input.size())
{
if(input[i] == ' ') continue;
if(isdigit(input[i]))
{
st.push(input[i]-'0');
}else{
op1 = st.top();
st.pop();
op2 = st.top();
st.pop();
switch(input[i])
{
case '+':
st.push(op1+op2);
break;
case '-':
st.push(op2-op1);//注意顺序
break;
case '*':
st.push(op1*op2);
break;
case '/':
st.push(op2/op1);
break;
default:
break;
}
}
i++;
}
return st.top();
}
本文没有把中缀表达式转为后缀表达式的代码,后续的文章会有介绍。