#define NULL 0
#include<string.h>
#include<stdio.h>
#include"stdlib.h"
typedef struct node
{
char e[100];
int top;
}linkstack;
typedef struct Node
{
float c[100];
int top;
}link;
char w[128];
int i;
char prec[8][8]={">><<<>>",">><<<>>",">>>><>>",
">>>><>>","<<<<<=@",">>>>@>>",
"<<<<<@=",">>>>>>>"};
char sign[]="+-*/()#";
char precede(char a,char b)
{
int i,j;
i=j=0;
while(sign[i]!=a) i++;
while(sign[j]!=b) j++;
return(prec[i][j]);
}
float numb()
{
int integer;
float decimal=0;
float sum=0;
if(w[i]>='0'&&w[i]<='9')
{
integer=w[i]-'0';
i++;
while(w[i]>='0'&&w[i]<='9')
{
integer=integer*10+w[i]-'0';
i++;
}
if(w[i]=='.')
{
float t=1.0;
i++;
while(w[i]>='0'&&w[i]<='9')
{
t=t/10;
decimal=decimal+(w[i]-'0')*t;
i++;
}
}
sum=integer+decimal;
return (sum);
}
else return(0);
}
void push1(linkstack *p,char c)
{
p->e[p->top++]=c;
}
void push2(link *p,float num)
{
p->c[p->top++]=num;
}
char gettop1(linkstack *optr)
{
char c;
c=optr->e[optr->top-1];
return(c);
}
float gettop2(link *opnd)
{
float num;
num=opnd->c[opnd->top-1];
return(num);
}
char pop1(linkstack *optr)
{
char c;
c=optr->e[--optr->top];
return(c);
}
float pop2(link *opnd)
{
float num;
num=opnd->c[--opnd->top];
return(num);
}
float operate(float a, char theta,float b)
{
float num;
switch (theta)
{
case '+':
num=b+a;
break;
case '-':
num=b-a;
break;
case '*':
num=a*b;
break;
case '/':
num=b/a;
break;
}
return num;
}
float evaluateexpression(void)
{
float num;
char theta;
float a,b;
linkstack s;
link t;
s.top=0;
t.top=0;
push1(&s,'#');
i=0;
while(w[i]!='#'||gettop1(&s)!='#')
{
num=numb();
if(num)
{
push2(&t,num);
}
else
switch(precede(gettop1(&s),w[i]))
{
case'<':
push1(&s,w[i++]);break;
case'=':
pop1(&s);i++;break;
case'>':
{
theta=pop1(&s);
a=pop2(&t);
b=pop2(&t);
push2(&t,operate(a,theta,b));
break;
}
}
}
return(gettop2(&t));
}
void main()
{
float x;
system("cls");
printf("表达式的计算!\n");
printf("输入表达式!\n");
scanf("%s",w);
x=evaluateexpression();
printf("=%f",x);
}