利用栈来实现算术表达式求值的算法用C语言实现。定义 函数 In(c):判断 c 是否为运算符和函数 Precede(t1,t2):判断运算符 t1 和 t2 的优先级还有 函数 Operate(a,theta,b):对 a 和 b 进行二元运算 theta。
时间: 2023-04-10 10:00:53 浏览: 152
可以回答这个问题。以下是C语言实现算术表达式求值的算法:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_SIZE 100
typedef enum {
false,
true
} bool;
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
bool isEmpty(Stack *s) {
return s->top == -1;
}
bool isFull(Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack *s, int x) {
if (isFull(s)) {
printf("Stack overflow!\n");
exit(EXIT_FAILURE);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow!\n");
exit(EXIT_FAILURE);
}
return s->data[s->top--];
}
int getTop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow!\n");
exit(EXIT_FAILURE);
}
return s->data[s->top];
}
int In(char c) {
switch (c) {
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
return true;
default:
return false;
}
}
char Precede(char t1, char t2) {
int i, j;
char table[][7] = {
{'>', '>', '<', '<', '<', '>', '>'},
{'>', '>', '<', '<', '<', '>', '>'},
{'>', '>', '>', '>', '<', '>', '>'},
{'>', '>', '>', '>', '<', '>', '>'},
{'<', '<', '<', '<', '<', '=', ' '},
{'>', '>', '>', '>', ' ', '>', '>'},
{'<', '<', '<', '<', '<', ' ', '='}
};
switch (t1) {
case '+':
i = 0;
break;
case '-':
i = 1;
break;
case '*':
i = 2;
break;
case '/':
i = 3;
break;
case '(':
i = 4;
break;
case ')':
i = 5;
break;
case '#':
i = 6;
break;
default:
printf("Invalid operator!\n");
exit(EXIT_FAILURE);
}
switch (t2) {
case '+':
j = 0;
break;
case '-':
j = 1;
break;
case '*':
j = 2;
break;
case '/':
j = 3;
break;
case '(':
j = 4;
break;
case ')':
j = 5;
break;
case '#':
j = 6;
break;
default:
printf("Invalid operator!\n");
exit(EXIT_FAILURE);
}
return table[i][j];
}
int Operate(int a, char theta, int b) {
switch (theta) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0) {
printf("Divide by zero!\n");
exit(EXIT_FAILURE);
}
return a / b;
default:
printf("Invalid operator!\n");
exit(EXIT_FAILURE);
}
}
int EvaluateExpression(char *expr) {
Stack opnd, optr;
char c, theta;
int a, b;
initStack(&opnd);
initStack(&optr);
push(&optr, '#');
c = *expr++;
while (c != '#' || getTop(&optr) != '#') {
if (!In(c)) {
int x = 0;
while (isdigit(c)) {
x = x * 10 + c - '0';
c = *expr++;
}
push(&opnd, x);
} else {
switch (Precede(getTop(&optr), c)) {
case '<':
push(&optr, c);
c = *expr++;
break;
case '=':
pop(&optr);
c = *expr++;
break;
case '>':
theta = pop(&optr);
b = pop(&opnd);
a = pop(&opnd);
push(&opnd, Operate(a, theta, b));
break;
default:
printf("Invalid operator!\n");
exit(EXIT_FAILURE);
}
}
}
return getTop(&opnd);
}
int main() {
char expr[STACK_SIZE];
printf("Enter an arithmetic expression: ");
scanf("%s", expr);
printf("The value of the expression is: %d\n", EvaluateExpression(expr));
return 0;
}
阅读全文