编写一个简单的C语言程序计算后缀表达式的值
时间: 2023-05-29 10:06:33 浏览: 44
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STACK_SIZE 100
typedef struct {
double data[MAX_STACK_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_STACK_SIZE - 1;
}
void push(Stack *s, double value) {
if (is_full(s)) {
printf("Stack overflow\n");
exit(EXIT_FAILURE);
}
s->data[++s->top] = value;
}
double pop(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
return s->data[s->top--];
}
double evaluate_postfix_expression(char *postfix) {
Stack s;
init(&s);
int i;
for (i = 0; postfix[i]; ++i) {
if (postfix[i] >= '0' && postfix[i] <= '9') {
push(&s, postfix[i] - '0');
} else {
double a = pop(&s);
double b = pop(&s);
switch (postfix[i]) {
case '+':
push(&s, b + a);
break;
case '-':
push(&s, b - a);
break;
case '*':
push(&s, b * a);
break;
case '/':
push(&s, b / a);
break;
default:
printf("Invalid operator: %c\n", postfix[i]);
exit(EXIT_FAILURE);
}
}
}
return pop(&s);
}
int main() {
char postfix[100];
printf("Enter postfix expression: ");
fgets(postfix, 100, stdin);
postfix[strcspn(postfix, "\n")] = '\0';
double result = evaluate_postfix_expression(postfix);
printf("Result: %f\n", result);
return 0;
}