我用#CSDN#这个app发现了有技术含量的博客,小伙伴们求同去《将中缀表达式转化成后缀表达式来计算值》, 一起来围观吧 https://blog.csdn.net/a884322916/article/details/104444301?utm_source=app&app_version=4.7.1&code=app_1562916241&uLinkId=usr1mkqgl919blen
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define maxn 100
char s[maxn];//存中缀表达式
char s1[maxn];//存后缀表达式的符号
char s2[maxn];//存符号的栈
int a[maxn];//存后缀表达式中的数字
int b[maxn];//用来计算最后的值
int judge(char op1,char op2) {//用来比较优先级,op1为栈顶符号,返回1则栈顶符号大
if (op1=='+'||op1=='-') {
if (op2=='+' || op2=='-') return 1;
else return 0;
} else if (op1=='(') return 0;
else return 1;
}
int main() {
int i,k,tmp=0;
int count=-1,top=-1;//标记栈顶
scanf("%s",s);
s[strlen(s)]='=';//手动添加最后一项
for (i=0;i<strlen(s);i++) {//开始扫描
if (!isdigit(s[i]) && isdigit(s[i-1])) {//存扫描的数字
a[++count]=tmp;
tmp=0;
s1[count]='a';//标记这一项存了数字
}
if (isdigit(s[i])) {//扫描数字得到值
tmp*=10;
tmp+=s[i]-'0';
}
else if (s[i]=='(') s2[++top]=s[i];//左括号直接入栈
else if (s[i]==')') {//右括号符号依次退栈存入s1中
while (s2[top]!='(') s1[++count]=s2[top--];
top--; //左括号退栈
}
else if (s[i]=='=') {//结尾符号全部退栈
while (top>=0) s1[++count]=s2[top--];
break;
}
else {//符号处理
if (top==-1) s2[++top]=s[i];//空栈则直接入
else {
while (judge(s2[top],s[i])==1) {//优先级比较
s1[++count]=s2[top--];//出栈
if (top==-1) break;
}
s2[++top]=s[i];//入栈
}
}
}
for (i=0;i<=count;i++) if (s1[i]=='a') printf("(%d)", a[i]); //输出后缀表达式中的数字
for (i=0;i<=count;i++) if (s1[i]!='a') printf("%c" ,s1[i]); //输出后缀表达式中的符号
printf("=\n");
for (i=0;i<=count;i++) {//对后缀表达式进行扫描计算
if (s1[i]=='a') b[++top]=a[i];//数入栈
else {
k=b[top];
if (s1[i]=='+') b[--top]+=k;
else if (s1[i]=='-') b[--top]-=k;
else if (s1[i]=='*') b[--top]*=k;
else b[--top]/=k;
}
}
printf("%d",b[top]);//完成
return 0;
}
//输入
//5+(3-2/1)*4
//输出
//(5)(3)(2)(1)(4)/-*+=
//9