制度下降算法c语言


#include
#include
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]);
}

运行结果:

制度下降算法c语言_第1张图片

你可能感兴趣的:(算法,数据结构,c语言,百度)