2 exqui site0416 exqui_site0416 于 2017.09.06 18:49 提问

请各位老手帮我看看我的代码有什么问题,为什么编译通过了但是运行有错误。

做的数据结构课程设计,中缀算术表达式求值但是课程还没有学,参考书上代码编的。
代码如下:
#include
#include
#include
#include
#define MAXSIZE 100
typedef int elemtype;
char ch[7] = { '+','-','*','/','(',')','#' };
int f1[7] = { 3,3,5,5,1,6,0 };
int f2[7] = { 2,2,4,4,6,1,0 };
int n = 0;
typedef struct sqstack
{ //顺序栈结构
elemtype stack[MAXSIZE];
int top;
}sqstack;
//1.把操作符转换成相应的数字
elemtype cton(char c)
{
switch (c)
{
case'+': return 0;
case'-': return 1;
case'*': return 2;
case'/': return 3;
case'(': return 4;
case')': return 5;
default: return 6;
}
}
//2.通过原来的设定比较两个字符的优先级
char Compare(char c1, char c2)
{
int i1 = cton(c1);
int i2 = cton(c2);
if (f1[i1] > f2[i2]) return '>';
else if (f1[i1] < f2[i2]) return '<';
else return '=';
}
//3.进行四则运算,并返回结果
int Operate(elemtype a, elemtype t, elemtype b)
{
int sum;
switch (t)
{
case 0: sum = a + b; break;
case 1: sum = a - b; break;
case 2: sum = a*b; break;
default: sum = a / b;
}
return sum;
}
//5.取栈顶元素
elemtype Gettop(sqstack s)
{
if (s.top == 0)
{
printf("ERROR,underflow\n"); return 0;
}
else
return s.stack[s.top];
}
//6.初始化栈
void Initstack(sqstack s)
{
s->top = 0;
}
//7.出栈
void Pop(sqstack *s, elemtype *x)
{
if (s->top == 0) printf("ERROR,Underflow\n");
else
{
*x = s->stack[s->top];
s->top--;
}
}
//8.入栈
void Push(sqstack *s, elemtype x)
{
if (s->top == MAXSIZE - 1) printf("ERROR,Overflow!\n");
else
{
s->top++;
s->stack[s->top] = x;
}
}
//9.若S为空栈,则返回TURE,否则返回FALSE
bool StackEmpty(sqstack S)
{
if (S.top == 0) return true;
else return false;
}
//4.主要的表达式计算函数,返回表达式计算结果
int EvaluateExpression()
{
char c;
int i = 0, sum = 0;
int k = 1, j = 1;
elemtype x, a, t, b;
sqstack OPTR, OPND;
Initstack(&OPTR);
Push(&OPTR, cton('#'));
Initstack(&OPND);
c = getchar();
while (c != '#' || ch[Gettop(OPTR)] != '#')
{
if (isdigit(c))
{
sum = 0;
while (isdigit(c))
{
if (!j)
{
sum = sum * 10 - (c - '0');
}
else sum = sum * 10 + (c - '0');
c = getchar();
}
Push(&OPTR, sum);
j = 1;
}
else if (k)
{
switch (Compare(ch[Gettop(OPTR)], c))
{
case'<':Push(&OPTR, cton(c));
c = getchar();
break;
case'=':Pop(&OPTR, &x);
c = getchar();
break;
case'>':Pop(&OPTR, &t);
Pop(&OPND, &b);
Pop(&OPND, &a);
Push(&OPND, Operate(a, t, b));
break;
}
}
}
return(Gettop(OPND));
}
//10.主函数
int main()
{
int result;
printf("
*********欢迎使用中缀算数表达式求值程序**********\n");
printf("请输入您要计算的表达式(以#号结束)\n");
result = EvaluateExpression();
printf("表达式的计算结果是:%d\n",result);
return 0;
}


1个回答

caozhy
caozhy   Ds   Rxr 2017.09.06 20:53
Csdn user default icon
上传中...
上传图片
插入图片