中缀表达式求值c++代码
时间: 2023-03-31 15:03:05 浏览: 156
C++实现中缀表达式求值
我可以回答这个问题。中缀表达式求值可以通过将中缀表达式转换为后缀表达式,然后再用栈来计算后缀表达式的值。以下是一个示例 C 代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
int top;
int data[MAX_SIZE];
} Stack;
void push(Stack *s, int x) {
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
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 ;
}
}
int evaluate(char *expression) {
Stack s;
s.top = -1;
int i, j, len, a, b, result;
char c, postfix[MAX_SIZE];
len = strlen(expression);
j = ;
for (i = ; i < len; i++) {
c = expression[i];
if (c >= '' && c <= '9') {
postfix[j++] = c;
} else if (is_operator(c)) {
while (s.top != -1 && is_operator(s.data[s.top]) && precedence(s.data[s.top]) >= precedence(c)) {
postfix[j++] = pop(&s);
}
push(&s, c);
} else if (c == '(') {
push(&s, c);
} else if (c == ')') {
while (s.top != -1 && s.data[s.top] != '(') {
postfix[j++] = pop(&s);
}
if (s.top == -1) {
printf("Unmatched parentheses\n");
exit(1);
}
pop(&s);
} else {
printf("Invalid character: %c\n", c);
exit(1);
}
}
while (s.top != -1) {
if (s.data[s.top] == '(') {
printf("Unmatched parentheses\n");
exit(1);
}
postfix[j++] = pop(&s);
}
postfix[j] = '\';
len = strlen(postfix);
s.top = -1;
for (i = ; i < len; i++) {
c = postfix[i];
if (c >= '' && c <= '9') {
push(&s, c - '');
} else if (is_operator(c)) {
b = pop(&s);
a = pop(&s);
switch (c) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
push(&s, result);
} else {
printf("Invalid character: %c\n", c);
exit(1);
}
}
if (s.top != ) {
printf("Invalid expression\n");
exit(1);
}
return pop(&s);
}
int main() {
char expression[MAX_SIZE];
printf("Enter an infix expression: ");
scanf("%s", expression);
int result = evaluate(expression);
printf("Result: %d\n", result);
return ;
}
```
阅读全文