c语言用栈字符串表达式计算,表达式计算(C语言版)代码
时间: 2023-12-21 08:03:48 浏览: 71
下面是使用栈实现字符串表达式计算的代码,包括将中缀表达式转换为后缀表达式和计算后缀表达式两部分:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 100
typedef struct {
int top;
char data[MAX_SIZE];
} Stack;
void push(Stack *s, char c) {
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow!\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top--];
}
char peek(Stack *s) {
if (s->top == -1) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top];
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
int precedence(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
void infix_to_postfix(char *infix, char *postfix) {
Stack s;
s.top = -1;
int i, j;
char c;
for (i = 0, j = 0; infix[i] != '\0'; i++) {
if (isdigit(infix[i])) {
postfix[j++] = infix[i];
} else if (infix[i] == '(') {
push(&s, infix[i]);
} else if (infix[i] == ')') {
while (!is_empty(&s) && (c = pop(&s)) != '(') {
postfix[j++] = c;
}
if (c != '(') {
printf("Mismatched parentheses!\n");
exit(1);
}
} else if (is_operator(infix[i])) {
while (!is_empty(&s) && precedence(infix[i]) <= precedence(peek(&s))) {
postfix[j++] = pop(&s);
}
push(&s, infix[i]);
} else {
printf("Invalid character in expression!\n");
exit(1);
}
}
while (!is_empty(&s)) {
c = pop(&s);
if (c == '(') {
printf("Mismatched parentheses!\n");
exit(1);
}
postfix[j++] = c;
}
postfix[j] = '\0';
}
double evaluate_postfix(char *postfix) {
Stack s;
s.top = -1;
int i;
char c;
double a, b;
for (i = 0; postfix[i] != '\0'; i++) {
if (isdigit(postfix[i])) {
push(&s, postfix[i] - '0');
} else if (is_operator(postfix[i])) {
b = pop(&s);
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 '/':
if (b == 0) {
printf("Division by zero!\n");
exit(1);
}
push(&s, a / b);
break;
case '^':
push(&s, pow(a, b));
break;
}
} else {
printf("Invalid character in expression!\n");
exit(1);
}
}
return pop(&s);
}
int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE];
printf("Enter an infix expression: ");
scanf("%s", infix);
infix_to_postfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
printf("Result: %g\n", evaluate_postfix(postfix));
return 0;
}
```
注意,在计算后缀表达式时,数字字符需要转换为数字,可以使用字符减去字符'0'的方式实现。此外,需要注意除数为零和括号匹配的情况。
阅读全文