前几天写的支持括号,但是只支持正整数
#include<stdio.h>#include<stdlib.h>
#include <ctype.h>
#define Stack_Size 50
typedef struct
{
char elem[Stack_Size];
int top;
}OpStack;
typedef struct
{
int elem[Stack_Size];
int top;
}NumStack;
void Push(OpStack *s,char x);
void Pop(OpStack *s,char *x);
void Push(NumStack *s,int x);
void Pop(NumStack *s,int *x);
int Execute(int a,char c,int b);
int ExpEvaluation(NumStack *OVS,OpStack *OPTR);
void GetNumber(char p);
int Cint(char mychar);
int num=0;
void main()
{
int result;
OpStack OPTR;
NumStack OVS;
OVS.top=-1;OPTR.top=-1;
result=ExpEvaluation(&OVS,&OPTR);
printf("The result is %d\n",result);
}
void Push(OpStack *s,char x)
{
s->top++;
s->elem[s->top]=x;
}
void Pop(OpStack *s,char *x)
{
*x=s->elem[s->top];
s->top--;
}
void Push(NumStack *s,int x)
{
s->top++;
s->elem[s->top]=x;
}
void Pop(NumStack *s,int *x)
{
*x=s->elem[s->top];
s->top--;
}
int Execute(int a,char c,int b)
{
switch(c)
{
case '+':return a+b;break;
case '-':return a-b;break;
case '*':;return a*b;break;
case '/':return a/b;break;
}
}
void GetNumber(char p)
{
num=num*10+Cint(p);
}
int Cint(char mychar)
{
return (mychar-48);
}
//栈运算符与读入运算符优先级的比较
char Compare(char x,char y)
{
char priority='<';
switch(x)
{
case '+':
case '-':if(y=='#'||y=='+'||y=='-'||y==')')priority='>';break;
case '*':
case '/': priority='>';if(y=='(' )priority='<';break;
case '(':if(y==')')priority='=';break;
case '#':if(y=='#') priority='=';break;
default:priority='E';
}
return priority;
}
int ExpEvaluation(NumStack *OVS,OpStack *OPTR)
{
int v,flag=0,f1=1,f2=1;
char ch,ch1,c;
int a,b,flag1=1;
Push(OPTR,'#');
printf("\n\nputin a string(stop with #):");
while(ch!='#'||OPTR->elem[OPTR->top]!='#')
{ if(f1&&f2)
ch=getchar();
if(isdigit(ch))
{
GetNumber(ch);
}
else
{
if((ch>='0'&&ch<='9'||ch1>='0'&&ch1<='9')&&!flag)
{
Push(OVS,num);
num=0;
}
switch(Compare(OPTR->elem[OPTR->top],ch))
{
case '<':
Push(OPTR,ch);
flag=0;
break;
case '>':
Pop(OPTR,&c);
Pop(OVS,&b);
Pop(OVS,&a);
v=Execute(a,c,b);
if(OPTR->elem[OPTR->top]=='-')
{
v=-1*v;
OPTR->elem[OPTR->top]='+';
}
Push(OVS,v);
if(ch!='#'&&ch!=')')
{
Push(OPTR,ch);
flag=0;
}
else
{
f1=0;
flag=1;
}
//printf("%d %c %d %d\n",a,c,b,v);
break;
case '=':
Pop(OPTR,&c);
if(c=='('&&ch==')')
{
f1=1;
flag=1;
}
break;
default:printf("Wrong Express!");exit(0);
}
}
ch1=ch;
}
return(v);
}
学习需要安静。。海盗要重新来过。。