运算规则:计算机首先将计算式转换成后缀码的形式,通过后缀码计算出结果。
eg:2+3*4/6+5 = 9
- 首先将该算式转化成对应的后缀码形式:234*6/+5+
1.转换规则:数字直接输出
2.碰到字符将符号入栈(
1.定义符号的优先级。
2.若栈为空时,直接入栈
3.非空则将入栈的符号与栈顶的比较,入栈元素大于等于栈顶元素则将栈顶元素出栈
)
2.计算后缀码,若是数字就将其入栈,当碰到数字的时,将栈顶2元素出栈做四则运算后入栈。
3.最后返回栈顶元素就是所求结果。
/*
定义优先级
*/
int op_prior(char c)
{
switch(c)
{
case ')':
return 3;
break;
case '*':
case '/':
return 2;
break;
case '+':
case '-':
return 1;
break;
default://非运算符
return 0;
break;
}
}
//将中缀码转换成后缀码
void change(char str[],char c[])
{
stack<char> st_a;
int L = strlen(c);
int j=0;//str数组的指针
for(int i=0; i<L; i++)
{
if(isdigit(c[i]))//如果是数字
{
str[j++] = c[i];
printf("%c",c[i]);
}
else if(op_prior(c[i]))//可能是运算符或者是符号
{
if(st_a.empty())
st_a.push(c[i]);//栈为空则入栈
else if(c[i] == ')')//等于有括号的时候
{
while(!st_a.empty()&&st_a.top()!='(')//将括号里面的内容全部出栈
{
//得到栈顶元素并出栈
str[j] = st_a.top();
st_a.pop();
printf("%c",str[j++]);
}
if(!st_a.empty())//将'('弹出栈
st_a.pop();
}//end else if
else//运算符的处理
{
while(!st_a.empty()&&st_a.top()!='('&&op_prior(st_a.top())>=op_prior(c[i]))//当栈顶元素的优先级大于等于将要入栈的元素时退栈
{
str[j] = st_a.top();
st_a.pop();
printf("%c",str[j++]);
}
st_a.push(c[i]);//将该运算符入栈
}
}//end else if
}//end for
//处理栈内剩余
while(!st_a.empty())
{
str[j] = st_a.top();
printf("%c",str[j++]);
st_a.pop();
}
}//end change
/*
栈的应用,求后缀式的值
*/
//计算2数的4则运算
double ops(double a,char op,double b)
{
if(op == '+')
return a+b;
else if(op == '-')
return a-b;
else if(op == '*')
return a*b;
else if(op == '/')
{
if(b==0)
return -999;
return a/b;
}
}
//计算
double com(char exp[])
{
stack<double> St;
char op;
int L = strlen(exp);
double a,b,c;
for(int i=0; i<L; i++)
{
if(exp[i]>='0'&&exp[i]<='9')
St.push(exp[i]-'0');
else
{
op = exp[i];//运算符
b = St.top();
St.pop();
a = St.top();
St.pop();
c = ops(a,op,b);
St.push(c);
}
}//end for
return St.top();
}