#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct
{
char *top;
char *base;
}OPTR;
typedef struct
{
float *base;
float *top;
}OPND;
void *initit_str(char **);
void *initit_TR(OPTR **);
void *initit_ND(OPND **);
void TR_push(char, OPTR *);
void TR_pop(OPTR *);
char TR_top(OPTR *);
void ND_push(float, OPND *);
void ND_pop(OPND *);
float ND_top(OPND *);
char Compare(char, char);
float Get_data(char **);
float Get_sum(float, char,float);
float Get_result(char *);
void main(void)
{
float data;
char *s;
initit_str(&s);
data=Get_result(s);
printf("\n结果: %5f\n",data);
return;
}
float Get_result(char *s)
{
float f1,f2,data;
char op,ch;
OPTR *TR;
OPND *ND;
initit_TR(&TR);
initit_ND(&ND);
TR_push('#',TR);
s++;
while(1)
{
if((*s)>='0' && (*s)<='9')
{
data=Get_data(&s);
ND_push(data,ND);
}
ch=Compare(TR_top(TR),(*s));
switch(ch)
{
case '=':
{
if(*s=='#')
return(ND_top(ND));
TR_pop(TR);
s++;
break;
}
case '<':
{
TR_push(*s,TR);
s++;
break;
}
case '>':
{
f2=ND_top(ND);
ND_pop(ND);
f1=ND_top(ND);
ND_pop(ND);
op=TR_top(TR);
TR_pop(TR);
data=Get_sum(f1,op,f2);
ND_push(data,ND);
break;
}
}
}
printf("结果:%10f\n",data);
}
void *initit_str(char **h)
{
(*h)=(char *)malloc(50*sizeof(char));
printf("输入表达式:\t");
scanf("%s",(*h));
return 0;
}
void *initit_TR(OPTR **h)
{
(*h)=(OPTR *)malloc(sizeof(OPTR));
(*h)->base=(char *)malloc(50*sizeof(char));
(*h)->top=(*h)->base;
return 0;
}
void *initit_ND(OPND **h)
{
(*h)=(OPND *)malloc(sizeof(OPND));
(*h)->base=(float *)malloc(50*sizeof(float));
(*h)->top=(*h)->base;
return 0;
}
void TR_push(char c,OPTR *h)
{
*(h->top++)=c;
return;
}
void TR_pop(OPTR *h)
{
(h->top)--;
return;
}
char TR_top(OPTR *h)
{
return(*(h->top-1));
}
void ND_push(float F, OPND *h)
{
*(h->top++)=F;
return;
}
void ND_pop(OPND *h)
{
(h->top)--;
return;
}
float ND_top(OPND *h)
{
return(*(h->top-1));
}
char Compare(char a, char b)
{
int i=0, j=0;
char s[7][7]={ {'>','>','<','<','<','>','>'},
{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=','0'},
{'>','>','>','>','0','>','>'},
{'<','<','<','<','<','0','='},
};
char r[7]={'+','-','*','/','(',')','#'};
while(a!=r[i])
i++;
while(b!=r[j])
j++;
return(s[i][j]);
}
float Get_data(char **h)
{
float f1=0,f2=0;
int i=1;
while((**h)>='0' && (**h)<='9')
{
f1=f1*10+((**h)-'0');
(*h)++;
}
if((**h)=='.')
{
(*h)++;
while((**h)>='0' && (**h)<='9')
{
i=i*10;
f2=f2+(float)((**h)-'0')/i;
(*h)++;
}
}
return(f1+f2);
}
float Get_sum(float f1, char ch, float f2)
{
if(ch=='+')
return(f1+f2);
if(ch=='-')
return(f1-f2);
if(ch=='*')
return(f1*f2);
else
return((float)f1/f2);
}