标签:
/*G[E]: E->E+T|E-T|T T->T*F|T/F|F F->(E)|i 左递归消除 E->TE‘ E‘->+TE‘|-TE‘|ε T->FT‘ T‘->*FT‘|/FT‘|ε F->(E)|i */ #include<stdio.h> char sym; char LL1[1000]; int N=-1; void T(); void E(); void F(); void e(); void t(); void error(); void scaner(); void main() { char ch; int i=0; printf("请输入需要分析的sym语法:(以#结束)\n"); do{ scanf("%c",&ch); LL1[i] = ch; i++; }while(ch != ‘#‘); scaner(); E(); if(sym == ‘#‘) printf("成功!\n"); else{ printf("文法有误!!\n"); error(); } } void scaner(){ //用于读取源函数的下一个字符 N++; if(LL1[N] == ‘ ‘){ N++; }else{ sym = LL1[N]; } } void E(){ T(); e(); } void T(){ F(); t(); } void e(){ if(sym == ‘+‘||sym == ‘-‘){ scaner(); T(); e(); } else if(LL1[N+1] == ‘#‘ || LL1[N+1] == ‘+‘ || LL1[N+1] == ‘/‘ || LL1[N+1] == ‘*‘ || LL1[N+1] == ‘-‘){ if(LL1[N] != ‘(‘ && LL1[N] != ‘)‘) error(); } } void t(){ if(sym == ‘*‘||sym == ‘/‘){ scaner(); F(); T(); } else if(LL1[N+1] == ‘#‘ || LL1[N+1] == ‘+‘ || LL1[N+1] == ‘/‘ || LL1[N+1] == ‘*‘ || LL1[N+1] == ‘-‘){ if(LL1[N] != ‘(‘ && LL1[N] != ‘)‘) error(); } } void F(){ if(sym == ‘(‘){ scaner(); E(); if(sym == ‘)‘){ scaner(); }else{ error(); } }else //判断是否是函数或者是数字 while(1){ if(sym >= ‘a‘ && sym<=‘z‘ || sym >= ‘A‘ && sym <= ‘Z‘ || sym >= ‘0‘ && sym <= ‘9‘){ scaner(); } else{ break; } } } void error(){ printf("第%d个 %c之后的文法有错!\n",N,sym); }
标签:
原文地址:http://www.cnblogs.com/cjh123/p/5089227.html