一、实验目的
将用中缀式表示的算术表达式转换为用逆波兰式表示的算术表达式,并计算用逆波兰式来表示的算术表达式的值
二、实验题目
如输入如下:21+((42-2)*15+6 )-18#
输出为:21+((42-2)*15+6)-18#
原来表达式: 21+((42-2)*15+6 )- 18#
21+((42-2)*15+6 )-18#
后缀表达式:21&42&2&-15&*6&++18&-
计算结果:609
参考程序代码:
#include<stdio.h> #include<math.h> #include<stdlib.h> #define max 100 char ex[max]; void trans() { char str[max]; char stack[max]; char ch; int sum,i,j,t,top=0; printf("请输入一个求值的表达式,以#结束。\n"); printf("算术表达式:"); i=0; ///*输入表达式 */ do { i++; scanf("%c",&str[i]); } while(str[i]!='#'&&i!=max); sum=i; t=1; i=1; ch=str[i]; i++; while(ch!='#') { switch(ch) { case '(':///判定为左括号 top++; stack[top]=ch; break; case ')':///判定为右括号 while(stack[top]!='(') { ex[t]=stack[top]; top--; t++; } top--; break; case '+':///判定为加减号 case '-': while(top!=0&&stack[top]!='(') { ex[t]=stack[top]; top--; t++; } top++; stack[top]=ch; break; case '*': case '/': while(stack[top]=='*'||stack[top]=='/') { ex[t]=stack[top]; top--; t++; } top++; stack[top]=ch; break; case ' ': break; default: while(ch>='0'&&ch<='9') { ex[t]=ch; t++; ch=str[i]; ///printf("%c\n",ch); i++; } i--; ex[t]='&'; t++; break;///添加break } ch=str[i]; i++; } while(top!=0)///扫描完毕时检查是否为空,不为空则一一出栈 { ex[t]=stack[top]; t++; top--; } ex[t]='#'; printf("\n\t 原来表达式:"); for(j=1; j<sum; j++) printf("%c",str[j]); printf("\n\t 后缀表达式:",ex); for(j=1; j<t; j++) printf("%c",ex[j]); } void compvalue() { float stack[max],d; char ch; int t=1,top=0; ch=ex[t]; t++; while(ch!='#') { switch(ch) { case '+': stack[top-1]=stack[top-1]+stack[top]; top--; break; case '-': stack[top-1]=stack[top-1]-stack[top]; top--; break; case '*': stack[top-1]=stack[top-1]*stack[top]; top--; break; case '/': if(stack[top]!=0) stack[top-1]=stack[top-1]/stack[top]; else { printf("\n\t 除0error!\n"); exit(0); } top--; break; default: d=0; while(ch>='0'&&ch<='9') { d=10*d+ch-'0'; ch=ex[t]; t++; } top++; stack[top]=d; } ch=ex[t]; t++; } printf("\n\t 计算结果:%g\n",stack[top]); getchar(); } int main() { trans(); compvalue(); getchar(); }