输入所求表达式后输入 # 为结尾表示输入结束
//表达式求值
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack &S){ //栈的初始化
S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base) exit (OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE ;
return OK;
}
int Push(SqStack &S,SElemType e){ //入栈
if(S.top-S.base>=S.stacksize){
S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base) exit (OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++ = e;
return OK;
}
int GetTop(SqStack S){ //取栈顶元素
SElemType e;
if(S.top==S.base) return ERROR;
e=*(S.top-1);
return e;
}
int Pop(SqStack &S,SElemType &e){ //出栈
if(S.base==S.top) return ERROR;
e=* --S.top;
return OK;
}
char Precede(char e,char c){//比较运算符优先级
char n;
switch(c){
case'+':
case'-':{if(e=='('||e=='#') n='<'; //c>e
else n='>';}break;
case'*':
case'/':{if(e=='*'||e=='/'||e==')') n='>';//c<e
else n='<';}break;
case'(':{if(e==')')
{
printf("括号不匹配\n");
exit(ERROR);
}
else n='<';} //c>e;
break;
case')':{if(e=='(') n='=';
else if(e=='#') {printf("缺少左括号\n");exit(ERROR);}
else n='>';
}//e>c
break;
case'#':{if(e=='#') n='=';
else if(e=='(') {printf("缺少右括号\n");exit(ERROR);}
else n='>';
} //e>c
}//switch
return n;
}
int Operate(int a,char theta,int b){//计算
switch(theta)
{
case'+':return a+b;break;
case'-':return a-b;break;
case'*':return a*b;break;
case'/':return a/b;break;
}
return OK;
}
int pp(int m,int n){
if(m-n>1)return 10*pp(m-1,n);
return 1;
}
int work(char s1[],int i,int p[]){
int j,sum=0;
for(j=p[i-1]+1;j<=p[i];j++){
if(s1[j]>='0'&&s1[j]<='9')
sum=sum+pp(p[i],j)*(int(s1[j]-48));
else
if((s1[j-1]>='0'&&s1[j-1]<='9'))
return sum;
}
return OK;
}
int EvaluateExpression(){
//算术表达式求值的算符优先算法,设置OPTR和OPND分别为运算符栈和运算数栈,
//设置OP为运算符集合
SqStack OPTR,OPND;
char OP[]={'+','-','*','/','(',')','#'};
char s1[100];
int a,b,X,theta;
int i,m=0,k=1,p[100];
p[0]=-1;
InitStack(OPTR);
InitStack(OPND);
Push(OPTR,'#');
for(i=0;;i++){//表达式输入
scanf("%c",&s1[i]);
if(s1[i]<'0'||s1[i]>'9')p[k++]=i;
if(s1[i]=='#')break;
}
while(s1[p[m]]!='#'||GetTop(OPTR)!='#') {//开始处理表达式
if(p[m+1]-p[m]!=1&&m!=k-1)//如果符号位不相邻且符号位没到末尾
Push(OPND,work(s1,m+1,p));
if(m!=k-1){m++;}
switch(Precede(GetTop(OPTR),s1[p[m]])){//开始处理符号
case '<':{ Push(OPTR,s1[p[m]]);
break;}
case '=':{ Pop(OPTR,X);
break;}
case '>':{ Pop(OPTR,theta);
Pop(OPND,a);
Pop(OPND,b);
Push(OPND,Operate(b,theta,a));
if(s1[p[m]]!='#') {
if(GetTop(OPTR)=='('&&s1[p[m]]==')') {Pop(OPTR,X);break;}
Push(OPTR,s1[p[m]]);
}
break;}
}//switch
}//while
return GetTop(OPND);
}//EvaluateExpression
void main(){
printf("请输入所需计算公式 以#结束输入");
printf("\n%d",EvaluateExpression());
printf("\n");
}