温馨提示×

C语言怎么用栈实现四则运算原理

小亿
112
2024-05-25 09:43:16
栏目: 编程语言

栈可以用来实现四则运算的计算过程,具体原理如下:

  1. 将中缀表达式转换为后缀表达式:使用栈来将中缀表达式转换为后缀表达式。遍历中缀表达式的每个元素,如果是数字直接输出,如果是操作符,则判断其优先级和栈顶操作符的优先级,根据优先级进行入栈或出栈操作,直到满足顺序后将操作符入栈。

  2. 计算后缀表达式:使用栈来计算后缀表达式。遍历后缀表达式的每个元素,如果是数字则入栈,如果是操作符则从栈中取出相应数量的操作数进行计算,并将结果入栈。

通过以上步骤,可以使用栈来实现四则运算的计算过程。以下是一个简单的C语言代码示例:

#include <stdio.h>
#include <stdlib.h>

// 定义栈结构
typedef struct {
    int top;
    int capacity;
    int *array;
} Stack;

// 创建栈
Stack* createStack(int capacity) {
    Stack* stack = (Stack*)malloc(sizeof(Stack));
    stack->top = -1;
    stack->capacity = capacity;
    stack->array = (int*)malloc(stack->capacity * sizeof(int));
    return stack;
}

// 判断栈是否为空
int isEmpty(Stack* stack) {
    return stack->top == -1;
}

// 入栈
void push(Stack* stack, int data) {
    stack->array[++stack->top] = data;
}

// 出栈
int pop(Stack* stack) {
    return stack->array[stack->top--];
}

// 计算后缀表达式
int evaluatePostfix(char* exp) {
    Stack* stack = createStack(100);
    int i = 0;
    int result = 0;

    while (exp[i] != '\0') {
        if (exp[i] >= '0' && exp[i] <= '9') {
            push(stack, exp[i]-'0');
        } else {
            int operand2 = pop(stack);
            int operand1 = pop(stack);
            switch(exp[i]) {
                case '+':
                    push(stack, operand1 + operand2);
                    break;
                case '-':
                    push(stack, operand1 - operand2);
                    break;
                case '*':
                    push(stack, operand1 * operand2);
                    break;
                case '/':
                    push(stack, operand1 / operand2);
                    break;
            }
        }
        i++;
    }

    result = pop(stack);
    free(stack->array);
    free(stack);
    return result;
}

int main() {
    char exp[] = "34+5*";
    printf("Result: %d\n", evaluatePostfix(exp));

    return 0;
}

以上代码演示了如何使用栈来计算后缀表达式,通过这种方式可以实现四则运算的计算过程。

0