平时我们常用的表达式都是中缀表达式,形如:(2+3)*4
但是在计算机中,后缀表达式会更容易运算。
例:
中缀表达式如何转化为后缀表达式:
从头到尾读取中缀表达式的各个对象,对不同的对象做不同的操作
①运算数:直接输出;
②左括号:压入堆栈;
③右括号:将栈顶的运算符弹出并输出,直到遇到左括号;
④运算符:
Ⅰ若优先级大于栈顶运算符,则压入堆栈;
Ⅱ若优先级小于等于栈顶运算符,将栈顶运算符弹出并输出,继续判断新的栈顶运算符,直到该运算符大于栈顶运算符,然后将该运算符压入堆栈;
⑤若各对象处理完毕,则把堆栈中剩余运算符一并输出。
代码实现:
#include <stdio.h>
#include <string.h>
#include<string.h>
#define MAX 100
// 设置符号优先级
int Compare_Priority(char c) {
if (c == '#') {
return 0;//表示中缀表达式已输入完毕
}
else if (c == '+' || c == '-') {
return 1;
}
else if (c == '*' || c == '/') {
return 2;
}
else if (c == '(' || c == ')') {
return 0;
}
else {
return -1;// 此时为数字
}
}
int main() {
char op[MAX];int top = -1;//初始化栈,只存运算符。
char str[MAX];//保存输入的中缀表达式
printf("输入中缀表达式,以#做输入结束的标志:");
scanf("%s", &str);
int len = strlen(str);//确定循环次数
printf("转化为后缀表达式:");
for (int i = 0;i < len;) {
if (Compare_Priority(str[i]) == -1) {
printf("%c", str[i++]);//是数字,直接输出
}
else if (str[i] == '(') {
op[++top] = str[i++];//是左括号,直接入栈
}
else if (str[i] == ')') {
while (op[top]!='(') {
printf("%c", op[top--]);//是右括号,找左括号
}
top--;
i++;
}
else {//是运算符
if (top == -1 || Compare_Priority(str[i]) > Compare_Priority(op[top])) {
op[++top] = str[i++];//优先级大于栈顶运算符,直接入栈
}
else {
while (Compare_Priority(str[i]) <= Compare_Priority(op[top]))
printf("%c", op[top--]);//优先级小于等于栈顶运算符,找大于的地方。
op[++top] = str[i++];//入栈
}
if (str[i] == '#') {
break;//结束标志
}
}
}
}