#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
int num_stack[MAX_SIZE];
int num_top = -1;
char op_stack[MAX_SIZE];
int op_top = -1;
void initStacks() {
num_top = -1;
op_top = -1;
}
bool pushNum(int n) {
if (num_top >= MAX_SIZE - 1) return false;
num_top++;
num_stack[num_top] = n;
return true;
}
int popNum() {
if (num_top == -1) return 0;
int val = num_stack[num_top];
num_top--;
return val;
}
bool isNumStackEmpty() {
return num_top == -1;
}
bool pushOp(char op) {
if (op_top >= MAX_SIZE - 1) return false;
op_top++;
op_stack[op_top] = op;
return true;
}
char popOp() {
if (op_top == -1) return '\0';
char op = op_stack[op_top];
op_top--;
return op;
}
bool isOpStackEmpty() {
return op_top == -1;
}
int applyOp(int a, int b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
case '^': {
int result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
default: return 0;
}
}
int getPrecedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
if (op == '^') return 3;
return 0;
}
void processOperators() {
while (!isOpStackEmpty()) {
char op = op_stack[op_top];
if (op == '(') break;
int b = popNum();
int a = popNum();
char op_char = popOp();
int result = applyOp(a, b, op_char);
pushNum(result);
}
}
int main() {
initStacks();
char ch;
printf("请输入算术表达式(以 # 结束,操作数为一位数字):\n");
ch = getchar();
while (ch != '#') {
if (ch >= '0' && ch <= '9') {
pushNum(ch - '0');
}
else if (ch == '(') {
pushOp(ch);
}
else if (ch == ')') {
while (!isOpStackEmpty() && op_stack[op_top] != '(') {
int b = popNum();
int a = popNum();
char op = popOp();
int res = applyOp(a, b, op);
pushNum(res);
}
if (!isOpStackEmpty()) {
popOp();
}
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^') {
while (!isOpStackEmpty() && op_stack[op_top] != '(' &&
getPrecedence(op_stack[op_top]) >= getPrecedence(ch)) {
int b = popNum();
int a = popNum();
char op = popOp();
int res = applyOp(a, b, op);
pushNum(res);
}
pushOp(ch);
}
ch = getchar();
}
while (!isOpStackEmpty()) {
int b = popNum();
int a = popNum();
char op = popOp();
int res = applyOp(a, b, op);
pushNum(res);
}
int result = popNum();
printf("表达式结果: %d\n", result);
return 0;
}