#include<stdio.h>
#include<string.h>
#define N 100
//计算出栈的元素
int Cal(int LX,int RX, char op){
if(op == '*') return LX * RX;
else if(op == '/') return LX / RX;
else if(op == '+') return LX + RX;
else if(op == '-') return LX - RX;
}
//求运算符优先级
int Level(char op){
switch (op){
case '*':
case '/': return 2;
case '+':
case '-': return 1;
case '(': return 0;
case '@': return -1;
}
}
//计算中缀表达式
int Calculate(char str[]){
char Sop[N]; //存储运算符的栈
int Sum[N]; //存储运算数的栈
int top1 = -1, top2 = -1;
Sop[++top1] = '@'; //运算符栈底初始化,保证表达式的运算符都能成功进栈
int i = 0, y, LX, RX;
char op;
//遍历中缀
while(str[i]){
//当str[i]为数字字符时,
if(str[i] <= '9' && str[i] >= '0'){
y = 0;
//用迭代法,将连续的数字字符转为整数
while(str[i] <= '9' && str[i] >= '0'){
y = y * 10 + str[i] - '0';
i++;
}
//将得到的整数压入运算数栈
Sum[++top2] = y;
i--; //将i回溯一个单位 ,因为大循环while有一个i++ 的自加运算
}
//当str[i]为 '(' 直接入运算符栈
else if(str[i] == '('){
Sop[++top1] = str[i];
}
//...........')' 则将括号内的表达式计算出来
else if(str[i] == ')'){
//依次将左括号之前的运算符出栈,并与运算栈栈顶的两个数予以计算
while(Sop[top1] != '('){
op = Sop[top1--];
RX = Sum[top2--];
LX = Sum[top2--];
Sum[++top2] = Cal(LX,RX,op); //将计算后的结果存入运算数栈
}
//括号内的算式计算完后,将左括号出栈
top1--;
}
else if(str[i] == '+' ||str[i] == '-'||str[i] == '*'||str[i] == '/'){
//当栈外运算符的优先级 低 于栈内运算符时
while (Level (str[i]) <= Level(Sop[top1])){
//栈内运算符出栈进行运算
op = Sop[top1--];
RX = Sum[top2--];
LX = Sum[top2--];
Sum[++top2]= Cal(LX,RX,op);
}
//当栈外运算符的优先级 高 于栈内运算符时
Sop[++top1] = str[i];
}
i++;
}
//遍历完中缀表达式后,将剩余没有处理的运算符和运算数依次出栈计算
while(top1){
op = Sop[top1--];
RX = Sum[top2--];
LX = Sum[top2--];
Sum[++top2] = Cal(LX,RX,op);
}
return Sum[top2];
}
int main(void){
char str[N]; //中缀表达式字符串
printf("\n请输入一个中缀表达式:");
gets(str);
int y = Calculate(str);
printf("%s = %d", str ,y);
return 0;
}