#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define MAXOP 100
#define Max 100
#define INFINITY 1e9
#define ERROR -1
typedef enum {false, true} bool;
typedef double ElementType;
typedef enum {num,opr,end}Type;
typedef int Position;
typedef struct SNode* PtrToSNode;
struct SNode{
ElementType *Data;
Position Top;
int Maxsize;
};
typedef PtrToSNode Stack;
Stack createstack(int Maxsize)
{
Stack s=(Stack)malloc(sizeof(struct SNode));
s->Data =(ElementType*)malloc(sizeof(ElementType)*Maxsize);
s->Top =-1;
s->Maxsize =Max;
return s;
}
bool IsFull(Stack s)
{
return (s->Top ==s->Maxsize -1);
}
bool push(Stack s,ElementType X)
{
if(IsFull(s)){
printf("FULL");
return false;
}else{
s->Data[++(s->Top )]=X;
return true;
}
}
bool IsEmpty(Stack s)
{
return (s->Top ==-1);
}
ElementType pop(Stack s)
{
if(IsEmpty(s)){
printf("Empty");
return ERROR;
}
else{
return (s->Data [(s->Top)--]);
}
}
Type Getop(char *Expr,int *start,char *str)
{
int i=0;
while((str[0]=Expr[(*start)++])==' ');
while(str[i]!=' '&&str[i]!='\0')
str[++i]=Expr[(*start)++];
if(str[i]=='\0')
(*start)--;
str[i]='\0';
if(i==0)
return end;
else if(isdigit(str[0])||isdigit(str[1]))
return num;
else
return opr;
}
ElementType PostfixExp(char *Expr)
{
Stack s;
Type T;
ElementType op1,op2;
char str[MAXOP];
int start=0;
s=createstack(MAXOP);
op1=op2=0;
while((T=Getop(Expr,&start,str))!=end)
{
if(T==num)
push(s,atof(str));
else{
if(!IsEmpty(s))
op2=pop(s);
else
op2=INFINITY;
if(!IsEmpty(s))
op1=pop(s);
else
op2=INFINITY;
switch(str[0]){
case'+':
push(s,op1+op2);
break;
case'*':
push(s,op1*op2);
break;
case'-':
push(s,op1-op2);
break;
case'/':
if(op2!=0.0)
push(s,op1/op2);
else{
printf("错误:除法分母为0\n");
op2=INFINITY;
}
break;
default:
printf("错误:未知运算符%s\n",str);
op2=INFINITY;
break;
}
if(op2>=INFINITY)
break;
}
}
if(op2<INFINITY)
if(!IsEmpty(s))
op2=pop(s);
else
op2=INFINITY;
free(s);
return op2;
}
int main()
{
char Expr[MAXOP];
ElementType f;
gets(Expr);
f=PostfixExp(Expr);
if(f<INFINITY)
printf("%.4f\n",f);
else{
printf("表达式错误\n");
}
return 0;
}