制度下降算法c语言

复制代码
#include<stdio.h>
#include<string.h>
int location=0;			//遍历字符串的当前位置
char arr[20]="id+id*id#";
void error();		//错误提示函数
/*
每一个非终结符都构造一个函数
*/
void E(char t);			
void Ep(char t);
void T(char t);
void Tp(char t);
void F(char t);

void E(char t){
    if(t=='('){
        printf("E->TE'");
        printf("\n");
        T(arr[location]);
        Ep(arr[location]);
    }else if(t=='i'){
        printf("E->TE'");
        printf("\n");
        T(arr[location]);
        Ep(arr[location]);
    }
    else{
        error();
        location++;
        E(arr[location]);
    }
}
void T(char t){
    if(t=='i'){
        printf("T->FT'");
        printf("\n");
        F(arr[location]);
        Tp(arr[location]);
    }else if(t=='('){
        printf("T->FT'");
        printf("\n");
        F(arr[location]);
        Tp(arr[location]);
    }else{
        error();
        location++;
        T(arr[location]);
    }
}
void Ep(char t){
    if(t=='+'){
        printf("E'->+TE'");
        printf("\n");
        location++;
        T(arr[location]);
        Ep(arr[location]);
    }else if(t==')'){
        printf("E'->&");
        printf("\n");
    }else if(t=='#'){
    }
    else{
        error();
        if(t=='i')
            location+=2;
        else
            location++;
        Ep(arr[location]);
    }
}
void Tp(char t){
    switch(t){
    case '+':
        printf("T'->&");
        printf("\n");
        break;
    case '*':
        printf("T'->*FT'");
        printf("\n");
        location++;
        F(arr[location]);
        Tp(arr[location]);
        break;
    case ')':
        printf("T'->&");
        printf("\n");
        break;
    case '#':
        printf("T'->&");
        printf("\n");
        break;
    default:
        error();
        if(t=='i')
            location+=2;
        else
            location++;
        Tp(arr[location]);
        break;
    }
}
void F(char t){
    if(t=='i'){
        printf("F->id");
        printf("\n");
        location+=2;
    }else if(t=='('){
        printf("F->(E)");
        printf("\n");
    }else{
        error();
        location++;
        F(arr[location]);
    }
}
void error(){
    printf("有一个错误,略过当前词法记号");
    printf("\n");
}
int main(){
    E(arr[location]);
}

运行结果:

相关推荐
yashuk4 分钟前
C语言入门教程:程序结构与算法举例
c语言·算法·教程·程序设计·开发过程
zsc_1187 分钟前
pvz3解码小游戏求解算法 (二)
算法
hanbr15 分钟前
每日一题day1(Leetcode 76最小覆盖子串)
算法·leetcode
AI科技星17 分钟前
张祥前统一场论中两个电荷定义的统一性解析
开发语言·线性代数·算法·数学建模·平面
代码地平线17 分钟前
C语言实现堆与堆排序详解:从零手写到TopK算法及时间复杂度证明
c语言·开发语言·算法
小江的记录本18 分钟前
【大语言模型】大语言模型——核心概念(预训练、SFT监督微调、RLHF/RLAIF对齐、Token、Embedding、上下文窗口)
java·人工智能·后端·python·算法·语言模型·自然语言处理
炘爚19 分钟前
LeetCode(两两交换链表中的节点)
算法·leetcode·链表
wsoz20 分钟前
Leetcode矩阵-day7
c++·算法·leetcode·矩阵
念越20 分钟前
算法每日一题 Day01|双指针解决移动零问题
java·算法·力扣
不想看见40421 分钟前
Merge k Sorted Lists 优先队列--力扣101算法题解笔记
笔记·算法·leetcode