产生式为L→En E→E1+T E→T T→T1F T→F F→E F→1 F→2 F→3 F→4 F→5利用LR分析法和语法制导翻译法实现简单算术表达式求值。例如:输入35+4+2n 输出29。生成完整c语言代码编写正确的代码能通过编译器验证
以下是完整的C语言代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
#define MAX_INPUT_SIZE 100
// 定义产生式
char productions[10][10] = {"L->En", "E->E1+T", "E->T", "T->T1*F", "T->F", "F->(E)", "F->1", "F->2", "F->3", "F->4", "F->5"};
// 定义符号栈结构体
typedef struct {
char stack[MAX_STACK_SIZE];
int top;
} Stack;
// 初始化符号栈
void initStack(Stack *s) {
s->top = -1;
}
// 判断符号栈是否为空
int isEmpty(Stack *s) {
return s->top == -1;
}
// 判断符号栈是否已满
int isFull(Stack *s) {
return s->top == MAX_STACK_SIZE - 1;
}
// 入栈
void push(Stack *s, char c) {
if (isFull(s)) {
printf("Error: Stack is full.\n");
exit(EXIT_FAILURE);
}
s->stack[++s->top] = c;
}
// 出栈
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Error: Stack is empty.\n");
exit(EXIT_FAILURE);
}
return s->stack[s->top--];
}
// 读取输入字符串
void readInput(char *input) {
printf("请输入要求值的算术表达式:");
scanf("%s", input);
}
// 获取下一个输入字符
char getNextChar(char *input, int *pos) {
return input[(*pos)++];
}
// 将字符转为数字
int charToInt(char c) {
return c - '0';
}
// 计算表达式的值
int calculate(Stack *s, char *input) {
int pos = 0;
char lookahead = getNextChar(input, &pos);
push(s, '$');
push(s, 'L');
while (lookahead != '$' && !isEmpty(s)) {
char top = s->stack[s->top];
if (top == lookahead) {
pop(s);
lookahead = getNextChar(input, &pos);
} else if (isupper(top)) {
int i, j;
for (i = 0; i < 11; i++) {
if (top == productions[i][0]) {
for (j = strlen(productions[i]) - 1; j >= 3; j--) {
push(s, productions[i][j]);
}
break;
}
}
} else if (isdigit(top)) {
int num = charToInt(top);
pop(s);
while (!isEmpty(s) && s->stack[s->top] == 'T') {
pop(s);
char op = pop(s);
int operand = charToInt(pop(s));
if (op == '*') {
num *= operand;
} else if (op == '/') {
num /= operand;
}
}
push(s, num + '0');
} else {
printf("Error: Invalid input.\n");
exit(EXIT_FAILURE);
}
}
return charToInt(s->stack[s->top]);
}
int main() {
char input[MAX_INPUT_SIZE];
readInput(input);
Stack s;
initStack(&s);
int result = calculate(&s, input);
printf("计算结果为:%d\n", result);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/g6V9 著作权归作者所有。请勿转载和采集!