首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言實現中綴表達式計算:轉後綴再求值

     編輯:關於C語言

兩步走策略

  1. 中綴轉後綴:利用運算符堆疊,按優先級與結合律輸出後綴表達式。
  2. 後綴求值:掃描後綴表達式,運算數入堆疊,遇運算符彈出兩個運算數計算,結果入堆疊。

完整代碼(支援 + - * / ^ 與括號)

#include <stdio.h>
#include <string.h>
#include <math.h>

#define MAX 10000

int val_stk[MAX], val_top = -1;
char op_stk[MAX], op_top = -1;
char infix[MAX], postfix[MAX];

void push_val(int v) { val_stk[++val_top] = v; }
int pop_val() { return val_stk[val_top--]; }
void push_op(char c) { op_stk[++op_top] = c; }
char pop_op() { return op_stk[op_top--]; }

int prec(char c) {
    if (c == '+' || c == '-') return 1;
    if (c == '*' || c == '/') return 2;
    if (c == '^') return 3;
    return 0;
}

void to_postfix() {
    int i, j = 0;
    for (i = 0; infix[i]; i++) {
        if (isdigit(infix[i])) {
            postfix[j++] = infix[i];
        } else if (infix[i] == '(') {
            push_op('(');
        } else if (infix[i] == ')') {
            while (op_top >= 0 && op_stk[op_top] != '(') {
                postfix[j++] = ' '; postfix[j++] = pop_op();
            }
            pop_op(); // 彈出 '('
        } else {
            while (op_top >= 0 && prec(op_stk[op_top]) >= prec(infix[i])) {
                postfix[j++] = ' '; postfix[j++] = pop_op();
            }
            push_op(infix[i]);
        }
        if (infix[i] != '(' && infix[i] != ')' && !isdigit(infix[i]))
            postfix[j++] = ' ';
    }
    while (op_top >= 0) {
        postfix[j++] = ' '; postfix[j++] = pop_op();
    }
    postfix[j] = '\0';
}

int eval_postfix() {
    int i = 0, num = 0;
    while (postfix[i]) {
        if (isdigit(postfix[i])) {
            num = 0;
            while (isdigit(postfix[i]))
                num = num * 10 + (postfix[i++] - '0');
            push_val(num);
        } else if (postfix[i] != ' ') {
            int b = pop_val(), a = pop_val();
            switch (postfix[i]) {
                case '+': push_val(a + b); break;
                case '-': push_val(a - b); break;
                case '*': push_val(a * b); break;
                case '/': push_val(a / b); break;
                case '^': push_val((int)pow(a, b)); break;
            }
            i++;
        } else i++;
    }
    return pop_val();
}

int main() {
    printf("輸入表達式: ");
    scanf("%s", infix);
    to_postfix();
    printf("後綴: %s\n", postfix);
    printf("結果: %d\n", eval_postfix());
    return 0;
}

測試樣例

輸入: 1+(3+2)*(7^2+6*9)/(2)
後綴: 1 3 2 + 7 2 ^ 6 9 * + 2 / * +
結果: 258

補充:批處理秒算法

Windows 下建立 calc.bat:

@echo off
set /p exp=
set /a ans=%exp%
echo %ans%
pause

可直接計算四則運算(不支援乘方)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved