一、實驗目的
將用中綴式表示的算術表達式轉換為用逆波蘭式表示的算術表達式,並計算用逆波蘭式來表示的算術表達式的值
二、實驗題目
如輸入如下: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(); }