ElementType EvalPostfix( char *expr ){
double s1[10],t;
int top1=-1,top2=-1,l=strlen(expr),neg=0;
char s2[10];
for(int i=0;i<l;){
if(expr[i]=='-'&&expr[i+1]!=' '&&i!=l-1){
neg=1;
i++;
}
else if(expr[i]=='+'||expr[i]=='*'||expr[i]=='/'||expr[i]=='-'){
if(top1==0)
return Infinity;
switch (expr[i]) {
case '+':
s1[top1-1]=s1[top1-1]+s1[top1];
break;
case '-':
s1[top1-1]=s1[top1-1]-s1[top1];
break;
case '*':
s1[top1-1]=s1[top1-1]*s1[top1];
break;
case '/':
if(s1[top1]==0)
return Infinity;
s1[top1-1]=s1[top1-1]/s1[top1];
break;
}
top1--;
i++;
}
else if(expr[i]>='0'&&expr[i]<='9'){
t=atof(expr+i);
while(expr[i]!=' '&&i<l){
i++;
}
if(neg){
neg=0;
t=-t;
}
s1[++top1]=t;
}
else{
i++;
}
}
if(top1==0)
return s1[0];
else
return Infinity;
}
6-5 Evaluate Postfix Expression (25 分)
最新推荐文章于 2022-07-21 18:53:39 发布