#include "stdafx.h"
#include "yunsuan.h"
#include "Evaluate.h"
#include <stdlib.h>
#include <string>
#include <stack>
using namespace std;
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define TRUE 1
#define FALSE 0
#define ERROR 0
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
////////////////////////////////////////////////////////////////////// Evaluate::Evaluate()
{ } Evaluate::~Evaluate()
{ }
int Evaluate::Precede(char m,char n)
{
char f;
switch(n)
{
case'+':
case'-':
if(m=='('||m=='=')
f='<';
else
f='>';
break;
case'*':
case'/':
if(m=='*'||m=='/'||m==')')
f='>';
else
f='<';
break;
case')':switch(m)
{
case'(':
f='=';
break;
case'=':
return ERROR;
default:
f='>';
}
break;
case'=':switch(m)
{
case'=':
f='=';
break;
case'(':
return ERROR;
default:
f='>';
}
}
return f;
}
int Evaluate::In(char c)
{
switch(c)
{
case'+':
case'-':
case'*':
case'/':
case'(':
case')':
case'=':return TRUE;
default:return FALSE;
}
}
int Evaluate::Operate(int a,char t,int b)
{
int s;
switch(t)
{
case'+':
s=a+b;
break;
case'-':
s=a-b;
break;
case'*':
s=a*b;
break;
case'/':
if(b=0)
return ERROR;
else
s=a/b;
}
return s;
} int Evaluate::EvaluateExpression()
{
stack<char>EXP;
stack<int>NUM;
char x;
char c;
char t;
int a,b,k;
CString s;
int i=1;
EXP.push('#');
x=EXP.top();
c=s.GetAt(i);
while(c!='#'||x!='#')
{
if(In(c))
switch(Precede(x,c))
{
case'<':
EXP.push(c);
i++;
c=s.GetAt(i);
break;
case'=':
x=EXP.top();
EXP.pop();
i++;
c=s.GetAt(i);
break;
case'>':
t=EXP.top();
EXP.pop();
b=NUM.top();
NUM.pop();
a=NUM.top();
NUM.pop();
NUM.push(Operate(a,t,b));
i++;
s.GetAt(i);
break;
}
else if(c>='0'&&c<='9')
{
s.Format(c);
NUM.push(c);
i++;
c=s.GetAt(i);
}
else
{
return ERROR;
}
x=EXP.top();
}
k=NUM.top();
return k;
} |