접두사 표현식 구해 MH

16403 단어 표현식
  1 #include<stdio.h>

  2 #include<stdlib.h>

  3 #define Stack_Size 100

  4 #define StackIncrement 10

  5 #define Ok 1

  6 #define Error 0

  7 #define Overflow -2

  8 #define True 1

  9 #define False -1

 10 typedef int status;

 11 // 

 12 typedef struct

 13 {

 14   float *base;

 15   float *top;

 16   int stacksize;

 17 }SqStack;

 18 status InitStack(SqStack &S)

 19 {

 20   S.base=(float *)malloc(Stack_Size*sizeof(float));

 21   if(!S.base)  exit(False);

 22   S.top=S.base;

 23   S.stacksize=Stack_Size;

 24   return Ok;

 25 }

 26 status StackEmpty(SqStack &S)

 27 {

 28   if(S.top==S.base)

 29   return True;

 30   return Error;

 31 }

 32 float GetTop(SqStack S)

 33 {

 34     float e;

 35     if(S.top==S.base)  return Error;

 36     e=*(S.top-1);

 37     return e;

 38 }

 39 status Push(SqStack &S,float e)

 40 {

 41   if((S.top-S.base)==S.stacksize)

 42   {

 43     S.base=(float *)realloc(S.base,(S.stacksize+StackIncrement)*sizeof(float));

 44     if(!S.base)  exit(False);

 45     S.top=S.base+S.stacksize;

 46     S.stacksize+=StackIncrement;

 47   }

 48   *S.top++=e;

 49   return Ok;

 50 }

 51 status Pop(SqStack &S,float &e)

 52 {

 53   if(S.top==S.base)  return Error;

 54   e=*--S.top;

 55   return Ok;

 56 }

 57 // 

 58 float Operate(float a,char theta,float b)

 59 {

 60     switch(theta)

 61     {

 62         case '+': return a+b;

 63         case '-': return a-b;

 64         case '*': return a*b;

 65         case '/': return a/b;

 66         default: return Error;

 67     }

 68 }

 69 status In(char c)

 70 {

 71     switch(c)

 72     {

 73         case '#':

 74         case ')':

 75         case '+':

 76         case '-':

 77         case '*':

 78         case '/':

 79         case '(': return True;

 80         case ' ': return False;

 81         default : return Error;

 82     }

 83 }

 84 float Evaluateexpression_r(char *S)

 85 {

 86     SqStack OPND;InitStack(OPND);

 87     float a,b; int k; char *p=S;

 88     char c=*p;

 89     while(c!='#')

 90     {

 91         if(!In(c))

 92         {

 93             for(k=0;In(c)!=-1;c=*++p)

 94             k=10*k+c-'0';

 95             Push(OPND,k);            

 96         }

 97         else

 98         {

 99             Pop(OPND,b);  Pop(OPND,a);

100             Push(OPND,Operate(a,c,b));

101         }

102         c=*++p;

103     }

104     return GetTop(OPND);

105 }

106 // 

107 status main()

108 {

109     char S[100];

110     float result;

111     puts(" :");

112     gets(S);

113     result=Evaluateexpression_r(S);

114     printf("%.2f
",result); 115 return Ok; 116 }

좋은 웹페이지 즐겨찾기