算数表达式文法的分析表,下图为i+i*i的分析过程:
4.结果截图:
语法正确的分析结果:
语法错误的分析结果:
5.源代码:
#define _CRT_SECURE_NO_WARNINGS #include
int ll1[5][6] = { { 1,0,0,1,0,0 }, { 0,2,0,0,3,3 }, { 4,0,0,4,0,0 }, { 0,6,5,0,6,6 },
{ 8,0,0,7,0,0 } }; //表示LL(1)分析表内容 int main() {
小
char ch[10] = { '#' , 'E' }; //用于存放符号栈内容 char str[10]; //存放输入串
char str1[10]; //用于存放最初输入的字符串 char cha; //分析字符
int i, j, m, n;//j:终结符所代表数字;m:非终结符所代表数字;n:产生式右部大int l = 1; //符号栈大小
int k = 1; //分析输入串的第几个字符 int how; //利用 哪 个产生式 int step = 1; //步骤 int length = 0;
printf(\请输入一串字符串,以#结尾:\); do {
scanf(\, &cha); str[length] = cha; str1[length] = cha; length++;
} while (cha != '#');
printf(\步骤\\t符号栈\\t当前输入符号\\t输入串\\t\\t所用产生式\\n\); do {
cha = str1[k - 1]; printf(\, step); for (i = 0; i <= l; i++)
printf(\, ch[i]); //输出符号栈 printf(\);
printf(\, cha);
for (i = 0; i < k; i++) { str[i] = ' ';
printf(\, str[i]); }
for (i = k; i case 'i': j = 0; break; case '+': j = 1; break; case '*': j = 2; break; case '(': j = 3; break; case ')': j = 4; break; case '#': j = 5; break; default: j = -1; break; } if (j != -1) //正确的字符 { if (ch[l] != cha) { if (ch[l] != 39) { switch (ch[l]) { case 'E': m = 0; break; case 'T': m = 2; break; case 'F': m = 4; break; default: m = -1; break; } } else { switch (ch[l - 1]) { case 'E': m = 1; break; case 'T': m = 3; break; default: m = -1; break; } } } if (m != -1) { if (ch[l] != cha) { how = ll1[m][j]; if (how == 1) { printf(\,ch[l]); n = 3; l = l + n - 1; ch[l] = 'T'; ch[l - 1] = 39; ch[l - 2] = 'E'; step = step + 1; } else if (how == 2) { printf(\reversing!\\n\,ch[l-1],ch[l]); n = 4; l = l + n - 2; ch[l] = '+'; ch[l - 1] = 'T'; ch[l - 2] = 39; ch[l - 3] = 'E'; step = step + 1; } else if (how == 3) { printf(\ε!\\n\,ch[l-1],ch[l]); l = l - 2; step = step + 1; } else if (how == 4) { printf(\,ch[l]); n = 3; l = l + n - 1; ch[l] = 'F'; ch[l - 1] = 39; ch[l - 2] = 'T'; step = step + 1; } else if (how == 5) { printf(\reversing!\\n\,ch[l-1],ch[l]); n = 4; l = l + n - 2;