注册 登录
编程论坛 新人交流区

[求助]C程序的一个错误,谢~!帮改一下

柒兲 发布于 2007-10-06 13:51, 305 次点击

/*实现功能`计算算术表达式的值*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAXSIZE 100

typedef char Elemtype;
typedef struct SqStack SqStack;
struct SqStack
{
int elem[MAXSIZE];
int top;
};

void InitStack(SqStack *s)
{

s->top=0;
}
void Push(SqStack *s,Elemtype x)
{

if(s->top==MAXSIZE-1)
printf("栈已满\n");
else
{
s->top++;
s->elem[s->top-1]=x;
}

}
int Pop(SqStack *s,Elemtype *y)
{

if(s->top==0)
return 0;
s->top--;
*y=s->elem[s->top];
return 1;

}


int Get_StackTop(SqStack *s)
{
Elemtype x;
if(s->top!=0)
{
x=s->elem[s->top];
return x;
}
else
{
printf("Eorror\n");
return 0;
}
}

int Opr(char c)
{
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='=')
return 0;
else
return 1;
}
char precede(char s,char c)
{
switch(s)
{
case'+':
case'-':
if(c=='+'||c=='-')
return '>';
else if(c=='*'||c=='/')
return '<';
else if(c=='(')
return '<';
else if(c==')')
return '>';
else
return '>';
case'*':
case'/':
if(c=='+'||c=='-')
return '>';
else if(c=='*'||c=='/')
return '>';
else if(c=='(')
return '<';
else if(c==')')
return '>';
else
return '>';
case '(':
if(c=='+'||c=='-')
return '<';
else if(c=='*'||c=='/')
return '<';
else if(c=='(')
return '<';
else if(c==')')
return '=';
else
return 'E';
case ')':
if(c=='+'||c=='-')
return '>';
else if(c=='*'||c=='/')
return '>';
else if(c=='(')
return 'E';
else if(c==')')
return '>';
else
return '>';
case '#':
if(c=='+'||c=='-')
return '<';
else if(c=='*'||c=='/')
return '<';
else if(c=='(')
return '<';
else if(c==')')
return 'E';
else
return '=';
default:
break;
}//switch
return 0;
}//preceed

int Operation(char *m,char *op,char *n)
{
int num;
int a=atoi(m);
int b=atoi(n);
switch(*op)
{
case'+':
num=a+b;
break;
case'-':
num=a-b;
break;
case'*':
num=a*b;
break;
case'/':
if(b==0)
{
printf("Eorror\n");
return 0;
}
else
{
num= a/b;
break;
}
default:
printf("In put eorror \n");
break;
}//switch
return num;
}//operation

void main()
{
char c,r;
char *x,*op;
char *a,*b;
int value;
SqStack *OPTR; //算符
SqStack *OPND; //运算数
OPTR=(SqStack *)malloc(sizeof(SqStack));
OPND=(SqStack *)malloc(sizeof(SqStack));
InitStack(OPTR);
Push(OPTR,'#');
InitStack(OPND);
c=getchar();
while(c!='#'||Get_StackTop(OPTR)!='#')
{
if(!Opr(c))
{
Push(OPND,c);
c=getchar();
}
else
{
r=precede(Get_StackTop(OPTR),c);
switch(r)
{
case'<':
Push(OPND,c);
c=getchar();
break;
case'=':
Pop(OPTR,x);
c=getchar();
case'>':
Pop(OPTR,op);
Pop(OPND,a);
Pop(OPND,b);
value=Operation(b,op,a);
Push(OPND,value);
break;
}//switch

}//else
}//wilte
printf("result = %d\n",Get_StackTop(OPND));
}

7 回复
#2
bobofei2007-10-06 13:58
我现在没有心思帮你读这么长的代码,我要到JAVA版去发言
#3
柒兲2007-10-06 14:03
#4
nuciewth2007-10-06 14:04
C程序的一个错误,谢~!帮改一下
是什么错误.
#5
gejianlin2007-10-06 14:39
#6
柒兲2007-10-06 14:39

逻辑错误啊`` 运行`结果不对``

#7
柒兲2007-10-06 14:45
回复:(柒兲)[em03]
逻辑错误啊` 结果不对哦``
#8
柒兲2007-10-06 14:46
回复:(柒兲)[em03]
逻辑错误``结果不对
1