严蔚敏版《数据结构》案例3.3:
题目:
以字符序列的形式从键盘输入语法正确的,不含变量的整型表达式。利用给出的算符优先关系,实现对算术四则混合运算表达式的求值。
算符优先矩阵:
代码:
此程序可以实现浮点数运算,关于求算符优先还有一种更方便的方法-----迭代法。
#include<stdio.h>
#define maxsize 1001
int In(char c){
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#')return 1;
else return 0;
}
char precede(char a,char b){
char opera[9][9]={
{'0','+','-','*','/','^','(',')','#'},
{'+','>','>','<','<','<','<','>','>'},
{'-','>','>','<','<','<','<','>','>'},
{'*','>','>','>','>','<','<','>','>'},
{'/','>','>','>','>','<','<','>','>'},
{'^','>','>','>','>','<','<','>','>'},
{'(','<','<','<','<','<','<','=','0'},
{')','>','>','>','>','>','0','>','>'},
{'#','<','<','<','<','<','<','0','='},};
int i,j;
for(i=0;i<10;i++){
if(opera[i][0]==a)break;
if(i==9)return -1;
}
for(j=0;j<10;j++){
if(opera[0][j]==b)break;
if(i==9)return -1;
}
return opera[i][j];
}
double computer(char op,double a,double b){
if(op=='+')return a+b;
else if(op=='-')return a-b;
else if(op=='*')return a*b;
else if(op=='^'){
int cnt=(int) b;
while(cnt--){
a*=a;
}
return a;
}
else return a/b;
}
int main(){
char *optr=new char[maxsize];
double *opnd=new double[maxsize],num1,num2;
int top1=-1,top2=-1,flag=1;;
optr[++top1]='#';
char c,op;
printf("请输入算术表达式以“#”号确认:");
scanf("%c",&c);
while(c!='#'||optr[top1]!='#'){
if(!In(c)){
opnd[++top2]=c-'0';
scanf("%c",&c);
int isdouble=0;
double cnt=10;
while((c-'0'>=0&&c-'0'<=9)||c=='.'){
if(c=='.'){
isdouble=1;
scanf("%c",&c);
continue;
}
if(isdouble==0)opnd[top2]=opnd[top2]*10+(c-'0');
else{
opnd[top2]=opnd[top2]+(c-'0')/cnt;
cnt*=10.0;
}
scanf("%c",&c);
}
}
else{
switch(precede(optr[top1],c)){
case'<':
optr[++top1]=c;
scanf("%c",&c);
break;
case'>':
op=optr[top1--];
if(top1<-1)
flag=0;
num2=opnd[top2--];
num1=opnd[top2--];
printf("%f%c%f\n",num1,op,num2);
if(top2<-1)flag=0;
opnd[++top2]=computer(op,num1,num2);
break;
case'=':
top1--;
if(top1<-1)
flag=0;
scanf("%c",&c);
break;
default:
flag=0;
}
}
if(flag==0)break;
}
if(flag==1)printf("%f\n",opnd[top2]);
else printf("ERROR\n");
return 0;
}