c语言栈实现四则运算
时间: 2023-07-28 15:06:29 浏览: 84
实现四则运算可以使用栈来辅助计算。具体实现如下:
1. 定义一个栈结构体,包含一个数组和一个栈顶指针:
```c
typedef struct {
int top;
int data[MAXSIZE];
} Stack;
```
2. 定义入栈和出栈操作:
```c
void push(Stack *s, int x) {
if (s->top == MAXSIZE - 1) {
printf("Stack is full.\n");
return;
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack is empty.\n");
return -1;
}
return s->data[s->top--];
}
```
3. 读入表达式,逐个字符处理:
```c
Stack num_stack; // 存储数字的栈
Stack op_stack; // 存储操作符的栈
char c = getchar();
while (c != '\n') {
if (isdigit(c)) { // 如果是数字,将其转换为整数并入栈
int num = c - '0';
c = getchar();
while (isdigit(c)) {
num = num * 10 + c - '0';
c = getchar();
}
push(&num_stack, num);
}
else if (c == '+' || c == '-' || c == '*' || c == '/') { // 如果是操作符
while (op_stack.top != -1 && priority(op_stack.data[op_stack.top]) >= priority(c)) { // 如果栈顶操作符的优先级不低于当前操作符,则出栈并计算
int b = pop(&num_stack);
int a = pop(&num_stack);
int op = pop(&op_stack);
int result = calculate(a, b, op);
push(&num_stack, result);
}
push(&op_stack, c);
c = getchar();
}
else { // 非法字符,忽略
c = getchar();
}
}
```
4. 处理完表达式后,计算栈中剩余的表达式:
```c
while (op_stack.top != -1) {
int b = pop(&num_stack);
int a = pop(&num_stack);
int op = pop(&op_stack);
int result = calculate(a, b, op);
push(&num_stack, result);
}
printf("%d\n", pop(&num_stack));
```
其中,`priority` 函数用来比较操作符的优先级,`calculate` 函数用来计算两个数的四则运算结果。完整代码如下: