#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. "); exit(EXIT_FAILURE); } s->stack[++s->top] = c; }

// 出栈 char pop(Stack *s) { if (isEmpty(s)) { printf("Error: Stack is empty. "); 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. "); 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/fYsj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录