修改后的代码如下:

#include <stdio.h> #include <string.h>

#define MAX_SIZE 100 // 表达式最大长度 #define MAX_STACK_SIZE 100 // 栈的最大容量 #define MAX_QUAD_SIZE 100 // 四元式序列的最大长度

// 定义符号栈和操作数栈 char symbol_stack[MAX_STACK_SIZE]; int symbol_top = -1; int operand_stack[MAX_STACK_SIZE]; int operand_top = -1;

// 定义四元式结构体 typedef struct { char op; // 操作符 int arg1; // 第一个操作数 int arg2; // 第二个操作数 int result; // 结果 } Quad;

// 定义四元式序列和当前指针 Quad quad_list[MAX_QUAD_SIZE]; int quad_ptr = 0;

// 获取符号的优先级 int get_priority(char c) { switch (c) { case '+': case '-': return 1; case '*': case '/': return 2; case '(': return 0; default: return -1; } }

// 将操作数入栈 void push_operand(int x) { operand_stack[++operand_top] = x; }

// 从操作数栈中弹出一个操作数 int pop_operand() { return operand_stack[operand_top--]; }

// 将符号入栈 void push_symbol(char c) { symbol_stack[++symbol_top] = c; }

// 从符号栈中弹出一个符号 char pop_symbol() { return symbol_stack[symbol_top--]; }

// 生成四元式 void gen_quad(char op, int arg1, int arg2, int result) { quad_list[quad_ptr].op = op; quad_list[quad_ptr].arg1 = arg1; quad_list[quad_ptr].arg2 = arg2; quad_list[quad_ptr].result = result; quad_ptr++; }

// 打印四元式序列 void print_quads() { printf("四元式序列:\n"); for (int i = 0; i < quad_ptr; i++) { printf("(%c, %d, %d, %d)\n", quad_list[i].op, quad_list[i].arg1, quad_list[i].arg2, quad_list[i].result); } }

// 对表达式进行语法分析,生成四元式序列 void analyze_expression(char* exp) { int i = 0; char c; while ((c = exp[i++]) != '\0') { if (c >= '0' && c <= '9') { // 数字直接入栈 int x = c - '0'; while (exp[i] >= '0' && exp[i] <= '9') { x = x * 10 + (exp[i] - '0'); i++; } push_operand(x); } else if (c == '+' || c == '-' || c == '*' || c == '/') { // 运算符 int pri = get_priority(c); while (symbol_top >= 0 && get_priority(symbol_stack[symbol_top]) >= pri) { char op = pop_symbol(); int arg2 = pop_operand(); int arg1 = pop_operand(); int result = operand_top + 1; push_operand(result); gen_quad(op, arg1, arg2, result); } push_symbol(c); } else if (c == '(') { // 左括号 push_symbol(c); } else if (c == ')') { // 右括号 while (symbol_top >= 0 && symbol_stack[symbol_top] != '(') { char op = pop_symbol(); int arg2 = pop_operand(); int arg1 = pop_operand(); int result = operand_top + 1; push_operand(result); gen_quad(op, arg1, arg2, result); } if (symbol_top >= 0 && symbol_stack[symbol_top] == '(') { pop_symbol(); } } } // 处理剩余的符号 while (symbol_top >= 0) { char op = pop_symbol(); int arg2 = pop_operand(); int arg1 = pop_operand(); int result = operand_top + 1; push_operand(result); gen_quad(op, arg1, arg2, result); } }

int main() { char exp[MAX_SIZE]; printf("请输入算术表达式:"); scanf("%s", exp); analyze_expression(exp); print_quads(); return 0; }

// 输入实例:2+3*(4-1)/5 // 输出结果: // 四元式序列: // (+, 2, , 2) // (-, 4, 1, 3) // (, 3, 5, 4) // (/, 2, 4, 5) // (+, 3, 5, 6


原文地址: https://www.cveoy.top/t/topic/gPyh 著作权归作者所有。请勿转载和采集!

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