#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
可直接計算四則運算(不支援乘方)。