用数据结构编写算术表达式得不出结果 大虾们看看错在哪了
#include<stdio.h>#include<stdlib.h>
#include<math.h>
#define maxlen 1000
typedef struct
{
char stack[maxlen];
int top;
}stack1;
typedef struct
{
int stack[maxlen];
int top;
}stack2;
stack1 *creat1()
{
stack1 *s;
s=(stack1 *)malloc(sizeof(stack1));
s->top=-1;
return s;
}
stack2 *creat2()
{
stack2 *s;
s=(stack2 *)malloc(sizeof(stack2));
s->top=-1;
return s;
}
int in(char c)
{
if((c=='+')||(c=='-')||(c=='*')||(c=='/')||(c=='#'))
return 1;
else
return 0;
}
void push1(stack1 *s,char ch)
{
(s->top)++;
s->stack[s->top]=ch;
}
void push2(stack2 *s,char ch)
{
(s->top)++;
s->stack[s->top]=ch;
}
void pop1(stack1 *s,char *a)
{
*a=s->stack[s->top];
(s->top)--;
}
void pop2(stack2 *s,int *a)
{
*a=s->stack[s->top];
(s->top)--;
}
char precede(char ch1,char ch2)
{
char ch;
switch(ch1)
{
case'+':if((ch2=='*')||(ch2=='/')||(ch2=='('))ch='<';else ch='>';break;
case'-':if((ch2=='*')||(ch2=='/')||(ch2=='('))ch='<';else ch='>';break;
case'*':if((ch2=='('))ch='<';else ch='>';break;
case'/':if((ch2=='('))ch='<';else ch='>';break;
case'#':if((ch2=='#'))ch='=';else ch='<';break;
}
return ch;
}
char gettop1(stack1 *s)
{
return (s->stack[s->top]);
}
char gettop2(stack2 *s)
{
return (s->stack[s->top]);
}
int operate(int a,char thrate,int b)
{
int s;
switch(thrate)
{
case'+':s=a+b;break;
case'-':s=a-b;break;
case'*':s=a*b;break;
case'/':s=a/b;break;
}
return s;
}
void main()
{
stack1 *OPTR;
stack2 *OPND;
int a,b,s;
char c,x,thrate;
OPTR=creat1();
OPND=creat2();
push1(OPTR,'#');
printf("请输入算术表达式并以#结束:\n");
c=getchar();
while((c!='#')||(gettop1(OPTR)!='#'))
{
if(!in(c))
{
s=c-'0';
push2(OPND,s);
c=getchar();
}
else
switch(precede(gettop1(OPTR),c))
{
case'<':push1(OPTR,c);c=getchar();break;
case'=':pop1(OPTR,&x);c=getchar();break;
case'>':pop1(OPTR,&thrate);pop2(OPND,&b);pop2(OPND,&a);push2(OPND,operate(a,thrate,b));break;
}
}
printf("结果为:\n");
c=gettop2(OPND);
}