以下代码为列志华先生提供严禁用于商业用途,除以盈利外的转载无任欢迎!!!!!
E→E+T|E-T|T
T→T*F| T/F|F
F→(E)|i
由给定文法G(x)转化的LL1文法为:
E->TE'
E'->+TE' | -TE' | §
T->FT'
T'->*FT | /FT' | §
F->(E) | i
#include<stdio.h> char curr; 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("请输入需要分析的curr语法:(以#结束)\n"); do{ scanf("%c",&ch); LL1[i] = ch; i++; }while(ch != '#'); scaner(); E(); if(curr == '#') printf("成功!\n"); else{ printf("文法有误!!\n"); error(); } } void scaner(){ //用于读取源函数的下一个字符 N++; if(LL1[N] == ' '){ N++; }else{ curr = LL1[N]; } } void E(){ T(); e(); } void T(){ F(); t(); } void e(){ if(curr == '+'){ scaner(); T(); e(); } else if(curr == '-'){ 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(curr == '*'){ scaner(); F(); T(); }else if(curr == '/'){ 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(); } } //LIE ZHI HUA TI GONG TAI MA void F(){ if(curr == '('){ scaner(); E(); if(curr == ')'){ scaner(); // printf("111111"); }else{ error(); } }else{ //判断是否是函数或者是数字 //error(); while(1){ if(curr >= 'a' && curr<='z' || curr >= 'A' && curr <= 'Z' || curr >= '0' && curr <= '9'){ scaner(); }else{ break; } } } } void error(){ printf("%d %c之后的文法有错!\n",N,curr); }