c语言用栈实现带括号的四则运算
时间: 2023-07-13 21:14:29 浏览: 93
c语言,实现带括号的四则运算的程序(使用Visual Studio )
好的,下面是一个C语言实现带括号的四则运算的代码,使用栈来处理表达式:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top;
} Stack;
void InitStack(Stack *s) {
s->top = -1;
}
int IsEmpty(Stack *s) {
return s->top == -1;
}
int IsFull(Stack *s) {
return s->top == MAXSIZE - 1;
}
void Push(Stack *s, int x) {
if (IsFull(s)) {
printf("Stack Overflow\n");
exit(1);
}
s->data[++(s->top)] = x;
}
int Pop(Stack *s) {
if (IsEmpty(s)) {
printf("Stack Underflow\n");
exit(1);
}
return s->data[(s->top)--];
}
int Top(Stack *s) {
if (IsEmpty(s)) {
printf("Stack Underflow\n");
exit(1);
}
return s->data[s->top];
}
int Priority(char op) {
if (op == '(' || op == ')')
return 0;
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return -1;
}
void InfixToPostfix(char *infix, char *postfix) {
Stack s;
InitStack(&s);
int i = 0, 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 (Top(&s) != '(')
postfix[j++] = Pop(&s);
Pop(&s);
i++;
}
else if (isspace(infix[i])) {
i++;
}
else {
while (!IsEmpty(&s) && Priority(Top(&s)) >= Priority(infix[i]))
postfix[j++] = Pop(&s);
Push(&s, infix[i++]);
}
}
while (!IsEmpty(&s))
postfix[j++] = Pop(&s);
postfix[j] = '\0';
}
int ComputePostfix(char *postfix) {
Stack s;
InitStack(&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 op1 = Pop(&s);
int op2 = Pop(&s);
switch (postfix[i]) {
case '+': Push(&s, op2 + op1); break;
case '-': Push(&s, op2 - op1); break;
case '*': Push(&s, op2 * op1); break;
case '/': Push(&s, op2 / op1); break;
default: printf("Invalid operator\n"); exit(1);
}
i++;
}
}
return Pop(&s);
}
int main() {
char infix[MAXSIZE], postfix[MAXSIZE];
printf("Enter an infix expression: ");
fgets(infix, MAXSIZE, stdin);
InfixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
int result = ComputePostfix(postfix);
printf("Result: %d\n", result);
return 0;
}
```
这个程序可以处理加、减、乘、除四则运算,同时支持括号,可以将中缀表达式转换成后缀表达式,并计算结果。
阅读全文