关键是将运算表达式转换成后缀表达式很难理解,12+12的后缀表达式为:12#12#+;
而(12.312-2.5)*4的后缀表达式为:12.312#2.5#-4#*,理解了这里就容易了!
#include <stdio.h> #define MAX 100 float strToFloat(char* string) { float poi=10.0; float strPoi=0.0; float strInt=0.0; while(*string!='/0'&&*string!='.') { strInt=strInt*10+*string-'0'; string++; } if(*string=='.') { string++; } while(*string!='/0') { strPoi=strPoi+(*string-'0')/poi; poi*=10; string++; } return strInt+strPoi; } void trans(char* expression,char* postExpression) { int i=0; struct { char data[MAX]; int top; }op; op.top=-1; while(*expression!='/0') { switch(*expression) { case '(': op.top++; op.data[op.top]= *expression; expression++; break; case ')': while(op.data[op.top]!='(') { postExpression[i]=op.data[op.top]; op.top--; i++; } op.top--; expression++; break; case '+': case '-': while(op.top!=-1&&op.data[op.top]!='(') { postExpression[i]=op.data[op.top]; i++; op.top--; } op.top++; op.data[op.top]=*expression; expression++; break; case '*': case '/': while(op.data[op.top]=='*'||op.data[op.top]=='/') { postExpression[i]=op.data[op.top]; i++; op.top--; } op.top++; op.data[op.top]=*expression; expression++; break; case ' ': break; default: while((*expression>='0'&&*expression<='9')||*expression=='.') { postExpression[i]=*expression; i++; expression++; } postExpression[i]='#'; i++; break; } } while(op.top!=-1) { postExpression[i]=op.data[op.top]; i++; op.top--; } postExpression[i]='/0'; } float calculate(char* postExpression) { char string[MAX]; float a,b,c,d; int e; struct { float data[MAX]; int top; }st; st.top=-1; while(*postExpression!='/0') { switch(*postExpression) { 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=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--; if(a==0) { printf("除零错误/n"); return 0; } else { c=b/a; st.top++; st.data[st.top]=c; } break; default: d=0; e=0; while((*postExpression>='0'&&*postExpression<='9')||*postExpression=='.') { string[e] = *postExpression; e++; postExpression++; } if(*postExpression=='#') { string[e] = '/0'; } d=strToFloat(string); st.top++; st.data[st.top]=d; break; } postExpression++; } return st.data[st.top]; } int main() { char postExpression[MAX]; char expression[MAX]; printf("请输入运算表达式:/n"); scanf("%s",expression); trans(expression,postExpression); printf("后缀表达式为:%s/n",postExpression); printf("运算结果为:%g/n",calculate(postExpression)); return 0; }