stack.h
#define N 100
typedef char CElemType;
typedef struct
{
CElemType a[N];
int top;
}CharStack;
void InitCharStack(CharStack *s)
{
s->top=-1;
}
int CharPush(CharStack *s,CElemType e)
{
if(s->top<N-1)
{
s->top++;
s->a[s->top]=e;
return 1;
}
else
{
return 0;
}
}
CElemType GetCharTop(CharStack *s)
{
if(s->top!=-1)
{
return s->a[s->top];
}
}
CElemType CharPop(CharStack *s)
{
CElemType e;
e=GetCharTop(s);
s->top--;
return e;
}
typedef double DElemType;
typedef struct
{
DElemType a[N];
int top;
}DataStack;
void InitDataStack(DataStack *s)
{
s->top=-1;
}
int DataPush(DataStack *s,DElemType e)
{
if(s->top<N-1)
{
s->top++;
s->a[s->top]=e;
return 1;
}
else
{
return 0;
}
}
DElemType DataPop(DataStack *s)
{
DElemType e;
if(s->top!=-1)
{
e=s->a[s->top];
s->top--;
return e;
}
}
cal.c
#include <stdio.h>
#include <math.h>
#include "stack.h"
int OperPos(char ch)
{
switch(ch)
{
case '+':return 0;
case '-':return 1;
case '*':return 2;
case '/':return 3;
case '(':return 4;
case ')':return 5;
case '#':return 6;
default:return 9;
}
}
char PriJuge(char stacktop,char beinstack)
{
int m,n;
char a[7][7]={
{'>','>','<','<','<','>','>'},
{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=','e'},
{'>','>','>','>','e','>','>'},
{'<','<','<','<','<','e','='}
};
m=OperPos(stacktop);
n=OperPos(beinstack);
return a[m][n];
}
double sum(double a,double b)
{
return a+b;
}
double sub(double a,double b)
{
return b-a;
}
double mul(double a,double b)
{
return a*b;
}
double div(double a,double b)
{
return b/a;
}
double Opera(double a,double b,char op)
{
char *ope="+-*/";
double (*func[4])(double,double)={sum,sub,mul,div};
int i;
for(i=0;ope[i]&&ope[i]!=op;i++);
if(i==strlen(ope))
{
printf("error:invalid operator/n");
return 0;
}
return func[i](a,b);
}
int Check(char *a)
{
int i,j=0;
char exp[100];
if(a[strlen(a)-1]!='#')
{
printf("error:express without '#'./n");
return 0;
}
for(i=0;a[i];i++)
{
if(a[i]!=' ')
exp[j++]=a[i];
}
for(i=0;exp[i];i++)
{
if(exp[i]=='(')
{
j=i+1;
for(;exp[j]&&exp[j]!=')';j++);
if(j==strlen(exp))
{
printf("error!/n");
return 0;
}
}
if(exp[i]>='a'&&exp[i]<='z')
{
printf("error!/n");
return 0;
}
}
}
void main()
{
char str[100];
char a[20];
int i,j=0,flag=0;
char pri,op;
double fir,sec,jg;
CharStack oper;
DataStack data;
InitCharStack(&oper);
InitDataStack(&data);
CharPush(&oper,'#');
printf("please input a express end with '#'./n");
gets(str);
if(!Check(str))
return ;
for(i=0;str[i];i++)
{
if(str[i]==' ')
continue;
if(str[i]>='0'&&str[i]<='9'||str[i]=='.')
{
a[j++]=str[i];
flag=1;
}
else
{
if(flag)
{
a[j]='/0';
DataPush(&data,atof(a));
j=0;
flag=0;
}
pri=PriJuge(GetCharTop(&oper),str[i]);
if(pri=='>')
{
op=CharPop(&oper);
fir=DataPop(&data);
sec=DataPop(&data);
DataPush(&data,Opera(fir,sec,op));
i--;
}
if(pri=='<')
{
CharPush(&oper,str[i]);
}
if(pri=='=')
{
op=CharPop(&oper);
}
}
}
jg=DataPop(&data);
printf("the resault is %f/n",jg);
}