请用C语言代码编写程序,执行按中缀形式输入一个四则运算的表达式,利用优选算法把其转换为后缀表达式输出,并求表达式的值。
时间: 2024-02-22 08:57:43 浏览: 20
好的,下面是使用C语言编写的程序,可以执行按中缀形式输入一个四则运算的表达式,利用优选算法把其转换为后缀表达式输出,并求表达式的值。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_SIZE 100
typedef struct stack {
char data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, char c) {
if (is_full(s)) {
printf("Error: stack is full!\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (is_empty(s)) {
printf("Error: stack is empty!\n");
exit(1);
}
return s->data[s->top--];
}
char peek(Stack *s) {
if (is_empty(s)) {
printf("Error: stack is empty!\n");
exit(1);
}
return s->data[s->top];
}
int priority(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
return 0;
default:
printf("Error: invalid operator %c\n", op);
exit(1);
}
}
void infix_to_postfix(char *infix, char *postfix) {
Stack s;
init(&s);
int i = 0;
int j = 0;
while (infix[i]) {
if (isdigit(infix[i])) {
postfix[j++] = infix[i++];
while (isdigit(infix[i])) {
postfix[j++] = infix[i++];
}
postfix[j++] = ' ';
} else if (infix[i] == '(') {
push(&s, infix[i++]);
} else if (infix[i] == ')') {
while (peek(&s) != '(') {
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
pop(&s);
i++;
} else if (isspace(infix[i])) {
i++;
} else {
while (!is_empty(&s) && priority(infix[i]) <= priority(peek(&s))) {
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
push(&s, infix[i++]);
}
}
while (!is_empty(&s)) {
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
postfix[j] = '\0';
}
int evaluate_postfix(char *postfix) {
Stack s;
init(&s);
int i = 0;
while (postfix[i]) {
if (isdigit(postfix[i])) {
int num = 0;
while (isdigit(postfix[i])) {
num = num * 10 + postfix[i] - '0';
i++;
}
push(&s, num);
} else if (postfix[i] == ' ') {
i++;
} else {
int b = pop(&s);
int a = pop(&s);
switch (postfix[i]) {
case '+':
push(&s, a + b);
break;
case '-':
push(&s, a - b);
break;
case '*':
push(&s, a * b);
break;
case '/':
push(&s, a / b);
break;
default:
printf("Error: invalid operator %c\n", postfix[i]);
exit(1);
}
i++;
}
}
return pop(&s);
}
int main() {
char infix[MAX_SIZE];
char postfix[MAX_SIZE];
printf("Please enter an infix expression: ");
fgets(infix, MAX_SIZE, stdin);
infix_to_postfix(infix, postfix);
printf("The postfix expression is: %s\n", postfix);
printf("The result is: %d\n", evaluate_postfix(postfix));
return 0;
}
```
输入一个中缀表达式,程序会将其转换为后缀表达式并输出,然后计算后缀表达式的值并输出。注意,程序假设输入的表达式没有语法错误。