栈的四则运算,求错误在哪。
做了个四则运算,居然连1+1都算出来都是负数,看了半天都不知道哪错了,我知道我肯定是做不出来加括号和负数小数的运算了。求解答哪里错了。代码附上,请看一看。
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "malloc.h"
#define MAX 100
typedef struct
{
int a[MAX];
int top;
}num_stack;
typedef struct
{
char b[MAX];
int top;
}str_stack;
void init_str(str_stack *s) //chu shi hua
{
s->top =-1;
}
void push_str(str_stack *s,char e) //ya zhan
{
s->b[++s->top]=e;
}
char pop_str(str_stack *s) //chu zhan
{
return(s->b[--s->top]);
}
char get_top(str_stack *s,char c)
{
c=s->b[--s->top];
return c;
}
// 数栈
void init_num(num_stack *s) //chu shi hua
{
s->top =-1;
}
void push_num(num_stack *s,char e) //ya zhan
{
s->a[++s->top]=e;
}
char pop_num(num_stack *s) //chu zhan
{
return(s->a[--s->top]);
}
int yunsuanfu(char a) //优先级
{
switch(a)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '#':
return 0;
default:
return 0;
}
}
int count(int a,char b,int c)
{
switch(b)
{
case '+':
return a+c;
case '-':
return a-c;
case '*':
return a*c;
case '/':
return a/c;
default:
return 0;
}
}
// pan duan
void panduan(num_stack *a,str_stack *b,char e[])
{
int i=0,k;
char m;
push_str(b,'#'); //算式后需要加一个#
while(e[i]!='#')
{
if(e[i]>='0'&&e[i]<='9')
{
k=e[i]-'0';
push_num(a,k);
}
/*else if(e[i]=='(')
push_str(b,'(');
else if(e[i]==')')
while(b->b[--b->top]!='(')
{
push_num(a,count(pop_num(a),pop_str(b),pop_num(a)));
}
*/
else if(yunsuanfu(e[i]))
{
if(yunsuanfu(e[i])>yunsuanfu(b->b[b->top-1]))
{
push_num(a,count(pop_num(a),e[i],e[i+1]-'0'));
i=i+1;
}
if(yunsuanfu(e[i])<=yunsuanfu(b->b[b->top-1]))
{
push_num(a,count(pop_num(a),pop_str(b),pop_num(a)));
}
}
i++;
}
}
void main()
{
char c[MAX];
int sum;
num_stack s1;
str_stack s2;
init_str(&s2);
init_num(&s1);
printf("请输入计算式 :");
scanf("%s",c);
panduan(&s1,&s2,c);
sum=pop_num(&s1);
printf("%d",sum);
system("pause");
}