制度下降算法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]);
}

运行结果:

相关推荐
Fanxt_Ja44 分钟前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 小时前
算法 --- 字符串
算法
博笙困了1 小时前
AcWing学习——差分
c++·算法
NAGNIP1 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP1 小时前
大模型微调框架之LLaMA Factory
算法
echoarts1 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客1 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法
徐小夕1 小时前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
嘀咕博客1 小时前
Zulu - 百度文心快码推出的自动编程智能体
百度·ai工具