#include <iostream>
#include <stack>
using namespace std;
/************************************************************************/
/* 表达式求值 */
/************************************************************************/
#define MaxSize 100
void trans(char exp[], char postexp[])
{
stack<char> op;
int i = 0, j = 0;
//op.top = -1;
while (*exp != '\0')
{
switch (*exp)
{
case '('://左括号进栈
op.push(*exp);
exp++;
break;
case ')'://将栈中“(”以前的运算符依次删除存入数组exp中,然后将“(”删除
while (!op.empty() && op.top() != '(')
{
postexp[i++] = op.top();
op.pop();
}
op.pop();
exp++;
break;
case '+':
case '-':
while (!op.empty() && op.top() != '(')
{//将栈中优先级大于等于‘+’或'-'的运算符退栈并存放到postexp中
postexp[i++] = op.top();
op.pop();
}
op.push(*exp);
exp++;
break;
case '*':
case '/':
while (!op.empty() && (op.top() == '*' || op.top() == '/'))
{//将栈中的“*”或者是“/”运算符依次出栈并存放到postexp中
postexp[i++] = op.top();
op.pop();
}
op.push(*exp);
exp++;
break;
case ' ':break;
default:
while (isdigit(*exp))
{
postexp[i++] = *exp;
exp++;
}
postexp[i++] = '#';
}
}
while (!op.empty())//最后的扫描工作
{
postexp[i++] = op.top();;
op.pop();;
}
postexp[i] = '\0';
cout << "后缀表达式" << endl;
for (j = 0; j < i; j++)
{
if(postexp[j]=='#')
j++;
cout << postexp[j];
}
cout << endl;
}
float compvalue(char postexp[])
{
stack<float> st;
float a, b, c, d;
while(*postexp != '\0')
{
switch(*postexp)
{
case '+':
a = st.top();
st.pop();
b = st.top();;
st.pop();;
c = a + b;
st.push(c);
break;
case '-':
a = st.top();
st.pop();
b = st.top();;
st.pop();;
c = b -a;
st.push(c);
break;
case '*':
a = st.top();
st.pop();
b = st.top();;
st.pop();;
c = a*b;
st.push(c);
break;
case '/':
a = st.top();
st.pop();
b = st.top();;
st.pop();;
if (a != 0)
{
c = b / a;
st.push(c);
}
else
{
cout << "除零错误!" << endl;
exit(0);
}
break;
default://进行最后的扫尾工作,将数字字符转换成数值存放到d中
d = 0;
while (isdigit(*postexp))
{
d = 10 * d + *postexp - '0';
postexp++;
}
st.push(d);
break;
}
postexp++;
}
return (st.top());
}
int main()
{
char exp[MaxSize]="((18+6)*2-9)/2";
char postexp[MaxSize]={0};
trans(exp, postexp);//exp存放中缀表达式,postexp存放后缀表达式
printf( "后缀表达式的值\n");
printf("%.2f\n", compvalue(postexp));
return 0;
}
数据结构:栈的典型应用之二:四则运算表达式求值(C++)
最新推荐文章于 2022-07-17 11:05:04 发布