中序表达式转换为逆波兰表达式,实现了基本的加减乘除以及括号的应用。
#include<iostream> using namespace std; #define MaxSize 100 #define MaxOp 7 struct{ char ch; int pri; } lpri[] = {{'=',0},{'(',1},{'*',5},{'/',5},{'+',3},{'-',3},{')',6}}, rpri[] = {{'=',0},{'(',6},{'*',4},{'/',4},{'+',2},{'-',2},{')',1}}; int leftpri(char op){ int i; for(i=0;i<MaxOp;i++) if(lpri[i].ch == op) return lpri[i].pri; } int rightpri(char op){ int i; for(i=0;i<MaxOp;i++) if(rpri[i].ch == op) return rpri[i].pri; } int InOp(char ch){ if(ch == '(' || ch == ')' ||ch == '+' || ch == '-' || ch == '*' || ch == '/') return 1; else return 0; } int Precede(char op1,char op2){ if(leftpri(op1) == rightpri(op2)) return 0; else if(leftpri(op1) < rightpri(op2)) return -1; else return 1; } void trans(char * exp,char postexp[]){ struct{ char data[MaxSize]; int top; }op; int i=0; op.top=-1; op.top++; op.data[op.top]='='; while(* exp != '\0'){ if(!InOp(* exp)){ while(* exp >= '0' && * exp <= '9'){ postexp[i++] = * exp; exp++; if(* exp == '.'){ postexp[i++] = * exp; exp++; } } postexp[i++]='#'; } else{ switch(Precede(op.data[op.top],* exp)){ case -1: op.top++; op.data[op.top] = * exp; exp++; break; case 0: op.top--; exp++; break; case 1: postexp[i++] = op.data[op.top]; op.top--; break; } } } while(op.data[op.top] != '='){ postexp[i++] = op.data[op.top]; op.top--; } postexp[i] = '\0'; } float calculated(char * postexp){ struct{ float data[MaxSize]; int top; }st; float d,a,b,c,e,f; st.top=-1; while(* postexp != '\0'){ switch(* postexp){ case '+': a=st.data[st.top]; st.top--; b=st.data[st.top]; st.top--; c=a+b; st.top++; st.data[st.top]=c; break; case '-': a=st.data[st.top]; st.top--; b=st.data[st.top]; st.top--; c=b-a; st.top++; st.data[st.top]=c; break; case '*': a=st.data[st.top]; st.top--; b=st.data[st.top]; st.top--; c=a*b; st.top++; st.data[st.top]=c; break; case '/': a=st.data[st.top]; st.top--; b=st.data[st.top]; st.top--; if(a != 0){ c=b/a; st.top++; st.data[st.top]=c; }else{ cout<<"除零错误!"<<endl; exit(0); } break; default: d=0; e=0; f=0; while(* postexp >= '0' && * postexp <= '9'){ d=10 * d+ *postexp-'0'; postexp++; if(* postexp == '.'){ postexp++; while(* postexp >= '0' && * postexp <= '9'){ f++; e=e * 10 + *postexp-'0'; postexp++; } for(int i=0;i<f;i++) e=e/10; } } d=d+e; st.top++; st.data[st.top]=d; break; } postexp++; } return st.data[st.top]; } int main(){ char exp[MaxSize]; char postexp[MaxSize]; float value = 0; cout<<"请输入你要计算的式子:"; cin>>exp; trans(exp,postexp); cout<<"转换成后缀表达式为:"<<postexp<<endl; value = calculated(postexp); cout<<"计算结果为:"<<value<<endl; return 0; }