|
<>#include<stdio.h><BR>#include<malloc.h></P>
<>#define null 0<BR>#define stack_size 100<BR>typedef struct{<BR> int *base;<BR> int *top;<BR> int stacksize;<BR>}stack;<BR>void init(stack *s){<BR> s->base=(int*)malloc(stack_size*sizeof(int));<BR> s->top=s->base;<BR> s->stacksize=stack_size;<BR>}</P>
<>char gettop(stack *s){<BR> char e;<BR> e=*(s->top-1);<BR> return e;<BR> <BR>}<BR>void push(stack *s,char e){<BR> *s->top++=e;<BR>}<BR>char pop(stack *s){<BR> char e;<BR> e=*--s->top;return e;}<BR> <BR>int compare(char e){<BR> char op[7]={'(',')','*','/','-','+','#'};<BR> int i=0;<BR> while(op!=e)i++;<BR> if(i>6)return 0;<BR> else return 1;<BR>}</P>
<P>int trust(char x){<BR> int a;<BR> switch(x){<BR> case '#': a=0;break;<BR> case '(': a=1;break;</P>
<P> case '+': a=2;break;</P>
<P> case '-': a=2;break;</P>
<P> case '*': a=3;break;</P>
<P> case '/': a=3;break;</P>
<P> case ')': a=4;break;</P>
<P> }<BR> return a;<BR>}<BR>char precede(char a,char b){<BR> int x,y;<BR> x=trust(a);<BR> y=trust(b);<BR> if(x==0&&y==0)return '=';<BR> if(x==1&&y==4)return '=';<BR> else<BR> if(x>y||x==y) return '>'; <BR> <BR> else<BR> return '<';<BR> <BR> }<BR> <BR>char operate(char a,char theta,char b){<BR> char r;<BR> switch(theta){<BR> case '+':r=a+b-'0';break;<BR> case '-':r=a+'0'-b;break;<BR> case '*':r=(a-'0')*(b-'0')+'0';break;<BR> case '/':r=(a-'0')/(b-'0')+'0';break;<BR> }<BR> return r;<BR>}<BR>char way(){<BR> stack *ch,*nb;char c,x,y,k,theta,a,b,l;<BR> ch=null;nb=null;<BR> </P>
<P> init(ch);push(ch,'#');<BR> init(nb);<BR> printf("请输入算术表达式,#表示结束\n");<BR> scanf("%c",&c);k=gettop(ch);<BR> while(c!='#'||k!='#'){<BR> if(compare(c)==0){push(nb,c);scanf("%c",&c);}<BR> else{<BR> l=precede(k,c);<BR> switch(l){<BR> case '<':push(ch,c);scanf("%c",&c);k=gettop(ch);break;<BR> case '=':pop(ch);scanf("%c",&c);k=gettop(ch);break;<BR> case '>':theta=pop(ch);b=pop(nb);a=pop(nb);<BR> x=operate(a,theta,b);push(nb,x);k=gettop(ch);break;<BR> }<BR> }getchar();<BR> }</P>
<P> y=gettop(nb);<BR> return y;<BR> <BR> } </P>
<P> <BR> </P>
<P>main(){<BR> char c;<BR> c=way();<BR> printf("算术表达式结果为: %c",c);<BR>}</P> |
|