本人新手一个,最近才开始上软件课,这是最近的一个简单计算器作业,然而输入式子后却总是显示“栈下溢”,有点怀疑是pop的原因,请各位大神教我,谢谢!!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <conio.h>
#include <ctype.h>
#define maxsize 50
typedef char datatype;
typedef struct
{
int data[maxsize];
int Top;
} SeqStack;
void InitStack(SeqStack*&S)
{
S = (SeqStack*)malloc(sizeof(SeqStack));
S->Top = 0;
}
int push(SeqStack*s,datatype e) //入栈函数
{
if (s->Top>=maxsize - 1)
{
printf("栈上溢");
return 0;
}
else
{
s->data[++s->Top] = e;
return 1;
}
}
char pop(SeqStack*s,datatype&e) //出栈函数
{
if (s->Top<=0)
{
printf("栈下溢");
return 0;
}
else
{
return e = s->data[s->Top--];
}
}
char GetTop(SeqStack*s,datatype&e) //取栈顶元素函数
{
if (s->Top<=0)
{
printf("栈下溢");
return 0;
}
else
{
e = s->data[s->Top];
return 1;
}
}
char precede(char top,char read) //比较栈顶元素和读取元素的优先级函数
{
switch(read)
{
case '#':
return '>';
case '+':
case '-':
if (top == '#')
{
return '<';
}
else
return '>';
case '*':
case '/':
if (top == '+'||top == '-'||top == '#')
{
return '<';
}
else
return '>';
}
}
char operate(char n1,char op,char n2) //运算函数
{
int sum;char s;
switch (op)
{
case '+':
sum = (n1 - 48) + (n2 - 48);
case '-':
sum = (n1 - 48) - (n2 - 48);
case '*':
sum = (n1 - 48) * (n2 - 48);
case '/':
sum = (n1 - 48) / (n2 - 48);
}
s = (char)sum;
return s;
}
int EvaluateExpression()
{
SeqStack *OPTR;
SeqStack *OPND;
InitStack(OPTR);
InitStack(OPND);
char ch;char top;char poper;
push (OPTR,'#');
while (((ch = getchar()) != '#')||GetTop(OPTR,top) != '#')
{
if (ch != '+'&&ch != '-'&&ch != '*'&&ch != '/'&&ch != '('&&ch !=')')
{
push (OPND,ch);
}
else
{
switch (precede(GetTop(OPTR,top),ch)) //判断优先级
{
case '<':
push (OPTR,ch);
break;
case '>':
char op = pop (OPTR,poper);
char b = pop (OPND,poper);
char a = pop (OPND,poper);
push (OPND,operate(a,op,b));
break;
}
}
}
int result = (int)GetTop(OPND,top);
return result;
}
int main()
{
int result;
printf("输入你的算术表达式,以#结束:\n");
result=EvaluateExpression();
printf("结果是 :%d\n",result);
return 0;
}