C语言:中缀表达式求值
时间: 2023-06-22 09:31:07 浏览: 265
中缀表达式求值需要使用栈来实现,以下是C语言实现中缀表达式求值的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
int stack[MAX_STACK_SIZE];
int top = -1;
void push(int value) {
if (top >= MAX_STACK_SIZE - 1) {
printf("栈已满\n");
exit(1);
}
top++;
stack[top] = value;
}
int pop() {
if (top < 0) {
printf("栈已空\n");
exit(1);
}
int value = stack[top];
top--;
return value;
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int precedence(char c) {
if (c == '*' || c == '/') {
return 2;
} else if (c == '+' || c == '-') {
return 1;
} else {
return 0;
}
}
int evaluate(char* expression) {
int i, num, num1, num2;
char c, op;
for (i = 0; expression[i] != '\0'; i++) {
c = expression[i];
if (isdigit(c)) {
num = 0;
while (isdigit(c)) {
num = num * 10 + c - '0';
i++;
c = expression[i];
}
i--;
push(num);
} else if (is_operator(c)) {
if (top < 1) {
printf("表达式错误\n");
exit(1);
}
num2 = pop();
num1 = pop();
op = c;
switch (op) {
case '+':
push(num1 + num2);
break;
case '-':
push(num1 - num2);
break;
case '*':
push(num1 * num2);
break;
case '/':
push(num1 / num2);
break;
}
}
}
if (top != 0) {
printf("表达式错误\n");
exit(1);
}
return pop();
}
int main() {
char expression[100];
int result;
printf("请输入中缀表达式:\n");
scanf("%s", expression);
result = evaluate(expression);
printf("结果为:%d\n", result);
return 0;
}
```
运行程序后,会提示用户输入中缀表达式,然后根据运算符优先级计算结果并输出。
阅读全文