3-7 表達式轉換 (20 分)

  • 2019 年 11 月 8 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/shiliang97/article/details/102484030

3-7 表達式轉換 (20 分)

算術表達式有前綴表示法、中綴表示法和後綴表示法等形式。日常使用的算術表達式是採用中綴表示法,即二元運算符位於兩個運算數中間。請設計程式將中綴表達式轉換為後綴表達式。

輸入格式:

輸入在一行中給出不含空格的中綴表達式,可包含+-*以及左右括弧(),表達式不超過20個字元。

輸出格式:

在一行中輸出轉換後的後綴表達式,要求不同對象(運算數、運算符號)之間以空格分隔,但結尾不得有多餘空格。

輸入樣例:

2+3*(7-4)+8/4

輸出樣例:

2 3 7 4 - * + 8 4 / +

不是我寫的,我也不會現在~~~~~

#include <stdio.h>  #include<stdlib.h>  #include<string.h>  void MainFum(char*,int);  int compare(char,char);  int IsNum(char);  int zhengfu(char);  int main() {      char a[21];//表達式不超過20個字元      scanf("%s",a);      int len=strlen(a);      MainFum(a,len);      return 0;  }  int IsNum(char c) {return (c>='0'&&c<='9')||c=='.';}  int zhengfu(char c) {return c=='+'||c=='-';}    int compare(char a,char b) {      if(b==')')return 1;      if(a=='('||b=='(')return 0;      switch(b) {          case '+':          case '-':              return 1;          case '*':          case '/':              switch(a) {                  case '+':                  case '-':                      return 0;                  case'*':                  case'/':                      return 1;              }      }  }  void MainFum(char*a,int lenth) {      static char stack[21];      static int flag=0;//指示棧容      static int i=0;//靜態局部變數,用於標記當前處理到字元串的哪一個位置      static int space =0;      for(; i<lenth; i++) {          if(IsNum(a[i])) {              if(space) {                  printf(" ");                  space =0;              }              printf("%c",a[i]);          } else if(zhengfu(a[i])&&(i?!IsNum(a[i-1])&&a[i-1]!=')':1)) {              if(a[i]=='-') {                  if(space) {                      printf(" ");                      space =0;                  }                  printf("%c",a[i]);//正號不輸出              }          } else { //一般符號              if(flag) {                  if(a[i]==')')                      while(flag--) {                          if(stack[flag]=='(')break;                          printf(" %c",stack[flag]);                      }                  else {                      while(flag) {                          if(compare(stack[flag-1],a[i])) {                              printf(" %c",stack[--flag]);                          } else break;                      }                      stack[flag++]=a[i];                  }                } else stack[flag++]=a[i];              for(int j=0; j<flag; j++)                  if(stack[j]!='(') {                      space=1;                      break;                  }          }      }      while(flag) {          printf(" %c",stack[--flag]);      }  }