用c语言实现:用栈完成从键盘输入一个算数表达式,完成用中缀表示法的表达式求值,其中表达式中数字可以为一位数,表达式中的运算符号包括+、-、*、/、(和)要求按照中缀表达式的顺序,计算出表达式的值,并输出至屏幕上
时间: 2024-01-24 12:17:22 浏览: 98
以下是用C语言实现用栈完成中缀表达式求值的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
void push(Stack *s, int value) {
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
s->top++;
s->data[s->top] = value;
}
int pop(Stack *s) {
int value;
if (s->top == -1) {
printf("Stack underflow\n");
exit(1);
}
value = s->data[s->top];
s->top--;
return value;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int precedence(char c) {
if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
} else {
return 0;
}
}
int evaluate(int op1, int op2, char operator) {
switch (operator) {
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '/':
return op1 / op2;
default:
printf("Unknown operator: %c\n", operator);
exit(1);
}
}
int evaluate_expression(char *expression) {
Stack operand_stack;
Stack operator_stack;
int i, j, value, op1, op2;
char c, operator;
init(&operand_stack);
init(&operator_stack);
for (i = 0; expression[i] != '\0'; i++) {
c = expression[i];
if (isdigit(c)) {
value = c - '0';
push(&operand_stack, value);
} else if (is_operator(c)) {
while (!is_empty(&operator_stack) && precedence(operator_stack.data[operator_stack.top]) >= precedence(c)) {
op2 = pop(&operand_stack);
op1 = pop(&operand_stack);
operator = pop(&operator_stack);
value = evaluate(op1, op2, operator);
push(&operand_stack, value);
}
push(&operator_stack, c);
} else if (c == '(') {
push(&operator_stack, c);
} else if (c == ')') {
while (operator_stack.data[operator_stack.top] != '(') {
op2 = pop(&operand_stack);
op1 = pop(&operand_stack);
operator = pop(&operator_stack);
value = evaluate(op1, op2, operator);
push(&operand_stack, value);
}
pop(&operator_stack);
}
}
while (!is_empty(&operator_stack)) {
op2 = pop(&operand_stack);
op1 = pop(&operand_stack);
operator = pop(&operator_stack);
value = evaluate(op1, op2, operator);
push(&operand_stack, value);
}
return pop(&operand_stack);
}
int main() {
char expression[MAX_SIZE];
printf("Enter an expression in infix notation: ");
scanf("%s", expression);
printf("Result: %d\n", evaluate_expression(expression));
return 0;
}
```
在这个代码中,我们使用两个栈:一个是操作数栈(operand_stack),用于存储表达式中的数字;另一个是操作符栈(operator_stack),用于存储表达式中的运算符和括号。我们从左到右扫描表达式,遇到数字就将其压入操作数栈中,遇到运算符或括号就根据其优先级进行相应的操作。具体来说,如果遇到一个运算符,我们就将其与操作符栈顶的运算符进行比较,如果栈顶运算符的优先级大于等于当前运算符的优先级,就将栈顶运算符弹出,并从操作数栈中弹出两个操作数,进行计算并将结果压入操作数栈中。如果遇到左括号,就将其压入操作符栈中;如果遇到右括号,就将操作符栈中的运算符弹出,直到遇到左括号,并从操作数栈中弹出两个操作数进行计算,将结果压入操作数栈中。最终,当表达式扫描完毕后,我们将操作符栈中的剩余运算符依次弹出,并从操作数栈中弹出两个操作数进行计算,将结果压入操作数栈中,最终操作数栈中只剩下一个元素,即表达式的值。
阅读全文