- #include<stdio.h>
- typedef struct
- {
- int *base,*top,stacksize;
- }Sqstack;
- char OP[]={'#",'+','-','*','/','(',')'};
- void Initstack(Sqstack &s)
- {
- s.base=(int*)malloc(sizeof(int));
- if(!s.base)
- printf("内存空间不足!!!!!");
- s.baes=s.top;
- s.stacksize=20;
- }
- void Push(Sqstack &s,char e)
- //*************压栈
- {
- if(s.top-s.base>=stacksize)
- printf("空间不足啊啊啊。。。!!!");
- *s.top++=e;
- }
- void GotTop(Sqstack s,char &e) //************读顶
- {
- if(s.base==s.top)
- printf("空栈!!!!!!!!!");
- e=*(s.top-1);
- }
- void Pop(Sqstack &s,char &e) //**********删除
- {
- if(s.base==s.top)
- printf("空栈!!!!!!!!!");
- e=*--s.top;
- }
- int In(char c)
- {
- int i;
- for(i=0;i<5;i++)
- if(c==OP[i])
- return 1;
- else
- return 0;
- }
- double EvaluateExpression()
- {
- char a,b,c,x;
- Initstack(OPTR);
- Push(OPTR,'#');
- Initstack(OPND);
- c=getchar();
- while(c!='#'||GotTop(OPTR)!='#')
- {
- if(!In(c))
- {
- Push(OPND,c);
- c=getchar();
- }
- else
- switch(Precede(GotTop(OPTR),c))
- {
- case'<':
- Push(OPTR,c);
- c=getchar();
- break;
- case'=':
- Pop(OPTR,x);
- Pop(OPND,b);
- Pop(OPND,a);
- Push(OPND,operate(a,x,b);
- Pop(OPTR,x);
- c=getchar();
- break;
- case'>':
- Pop(OPTR,x);
- Pop(OPND,b);
- Pop(OPND,a);
- Push(OPND,operate(a,x,b);
- break;
- }
- return GetTop(OPND);
- }
- void main()
- {
- double y=0.0;
- Sqstack OPTR,OPND;
- printf("输入一个表达式:");
- y=EvaluateExpression();
- printf("表达式的值为:%d",y);
- }
- //该片段来自于http://www.codesnippet.cn/detail/060620133848.html
来源: http://www.codesnippet.cn/detail/060620133848.html