用c语言设计一个程序,演示用算符优先法对算术表达式求值的过程
时间: 2023-12-14 22:37:30 浏览: 106
以下是使用算符优先法对算术表达式求值的C语言程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef struct {
int top;
char data[MAX_STACK_SIZE];
} Stack;
void initStack(Stack *stack) {
stack->top = -1;
}
void push(Stack *stack, char c) {
if (stack->top >= MAX_STACK_SIZE - 1) {
printf("Stack overflow!\n");
exit(1);
}
stack->data[++stack->top] = c;
}
char pop(Stack *stack) {
if (stack->top < 0) {
printf("Stack underflow!\n");
exit(1);
}
return stack->data[stack->top--];
}
int isEmpty(Stack *stack) {
return stack->top < 0;
}
char stackTop(Stack *stack) {
if (stack->top < 0) {
printf("Stack underflow!\n");
exit(1);
}
return stack->data[stack->top];
}
int getPriority(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
int evaluate(char *expr) {
Stack opStack;
initStack(&opStack);
Stack valStack;
initStack(&valStack);
while (*expr != '\0') {
if (isdigit(*expr)) {
int val = 0;
while (isdigit(*expr)) {
val = val * 10 + (*expr - '0');
expr++;
}
push(&valStack, val);
} else if (*expr == '(') {
push(&opStack, *expr);
expr++;
} else if (*expr == ')') {
while (stackTop(&opStack) != '(') {
char op = pop(&opStack);
int val2 = pop(&valStack);
int val1 = pop(&valStack);
int result = 0;
switch (op) {
case '+':
result = val1 + val2;
break;
case '-':
result = val1 - val2;
break;
case '*':
result = val1 * val2;
break;
case '/':
result = val1 / val2;
break;
}
push(&valStack, result);
}
pop(&opStack); // Pop the left parenthesis
expr++;
} else if (*expr == '+' || *expr == '-' || *expr == '*' || *expr == '/') {
while (!isEmpty(&opStack) && getPriority(stackTop(&opStack)) >= getPriority(*expr)) {
char op = pop(&opStack);
int val2 = pop(&valStack);
int val1 = pop(&valStack);
int result = 0;
switch (op) {
case '+':
result = val1 + val2;
break;
case '-':
result = val1 - val2;
break;
case '*':
result = val1 * val2;
break;
case '/':
result = val1 / val2;
break;
}
push(&valStack, result);
}
push(&opStack, *expr);
expr++;
} else {
printf("Invalid character %c!\n", *expr);
exit(1);
}
}
while (!isEmpty(&opStack)) {
char op = pop(&opStack);
int val2 = pop(&valStack);
int val1 = pop(&valStack);
int result = 0;
switch (op) {
case '+':
result = val1 + val2;
break;
case '-':
result = val1 - val2;
break;
case '*':
result = val1 * val2;
break;
case '/':
result = val1 / val2;
break;
}
push(&valStack, result);
}
return pop(&valStack);
}
int main() {
char expr[100];
printf("Enter an arithmetic expression: ");
scanf("%s", expr);
int result = evaluate(expr);
printf("Result: %d\n", result);
return 0;
}
```
该程序定义了一个栈结构体,实现了栈的基本操作(初始化、入栈、出栈、判断栈是否为空、获取栈顶元素)。还定义了一个getPriority()函数,用于获取操作符的优先级。evaluate()函数是主要实现算符优先法求值的函数,它先将中缀表达式转换为后缀表达式,然后用后缀表达式求值。在evaluate()函数中,用两个栈分别存储操作符和操作数,并根据操作符的优先级来决定入栈还是出栈。最后,将结果从操作数栈中弹出即为表达式的值。程序还实现了对非法字符的处理。
阅读全文