D - 表达式语法分析——递归子程序法

  1 #include <string.h>
  2 #include <stdio.h>
  3 #include <stdlib.h>
  4 char str[100];
  5 int c,num;
  6 void E();
  7 void G();
  8 void T();
  9 void S();
 10 void F();
 11 int main()
 12 {
 13     scanf("%s",str);
 14     E();
 15     if(str[c]=='#')
 16         printf("accept\n");
 17     else
 18         printf("error\n");
 19         return 0;
 20     }
 21 void E()
 22 {
 23     if(str[c]=='('||str[c]=='i')
 24     {
 25         printf("%d E-->TG\n",num);
 26         num++;
 27         T();
 28         G();
 29     }
 30     else
 31     {
 32         printf("error\n");
 33         exit(0);
 34     }
 35 }
 36 
 37 void G()
 38 {
 39     if(str[c]=='+')
 40     {
 41         c++;
 42         printf("%d G-->+TG\n",num);
 43         num++;
 44         T();
 45         G();
 46     }
 47     else
 48     {
 49         printf("%d G-->&\n",num);
 50         num++;
 51     }
 52 }
 53 
 54 void T()
 55 {
 56     if(str[c]=='('||str[c]=='i')
 57     {
 58         printf("%d T-->FS\n",num);
 59         num++;
 60         F();
 61         S();
 62     }
 63     else
 64     {
 65         printf("error\n");
 66         exit(0);
 67     }
 68 }
 69 void S()
 70 {
 71     if(str[c]=='*')
 72     {
 73         c++;
 74         printf("%d S-->*FS\n",num);
 75         num++;
 76         F();
 77         S();
 78     }
 79     else
 80     {
 81         printf("%d S-->&\n",num);
 82         num++;
 83     }
 84 }
 85 void F()
 86 {
 87     if(str[c]=='(')
 88     {
 89         c++;
 90         printf("%d F-->(E)\n",num);
 91         num++;
 92         E();
 93         if(str[c]==')')
 94         {
 95             c++;
 96         }
 97         else
 98         {
 99             printf("error\n");
100             exit(0);
101         }
102     }
103     else if (str[c]=='i')
104     {
105         c++;
106         printf("%d F-->i\n",num);
107         num++;
108     }
109     else
110     {
111         printf("error\n");
112         exit(0);
113     }
114 }

 

posted @ 2021-10-20 15:33  念文丶  阅读(183)  评论(0编辑  收藏  举报