表达式求值(上)

王朝vc·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

/* 功能:计算包含变量及函数的表达式

2>变量之间允许有表达式约束

使用说明:

1>用户使用的函数为bool CExpression::CalExp()

double m_dResult; file://计算得数

char* m_strExp; file://表达式字符串

CVarList m_VarList; file://变量表

bool m_bDegUnit; // 缺省采用角度单位

CVar var1

出错返回false,

2>用户使用该函数前负责初始化变量表

例如:用户有变量a=10,b=2,c=20.其中c=a*b;

则用户做如下工作:

CVar *pVar;

pVar=new CVar;

pVar->m_dValue=10;

pVar->m_strName="a";

CExpression exp1;

exp1.m_VarList.AddVar(pVar);

pVar=new CVar;

pVar->m_dValue=20;

pVar->m_strName="b";

exp1.m_VarList.AddVar(pVar);

pVar=new CVar;

pVar->m_dValue=0;

pVar->m_strName="c";

pVar->m_strSlave="a*b";

exp1.m_VarList.AddVar(pVar);

exp1.m_strExp="a*b+c";

exp1.CalExp();

计算出表达式的左值.*

3>被其他变量约束的变量在变量表中的位置应放在相关变量之后. */

// Expression.h: interface for the CExpression class.

//

//////////////////////////////////////////////////////////////////////

#if !defined(AFX_EXPRESSION_H__2578E33F_FF86_4384_A7CE_A401BAC5A010__INCLUDED_)

#define AFX_EXPRESSION_H__2578E33F_FF86_4384_A7CE_A401BAC5A010__INCLUDED_

#if _MSC_VER > 1000

#pragma once

#endif // _MSC_VER > 1000

#include <list>

#include <string>

using namespace std;

#define DELIMITER 1 //分隔符

#define VARIABLE 2 //变量

#define NUMBER 3 //数值

#define FUNCTION 4 //函数

#define PI 3.1415926535898

class CVar //用来存放变量及变量值的表结构

{

public:

char m_cFlag; // 等于0为临时变量,否则等于1

string m_strName; //变量名 如变量a

string m_strSlave; //约束表达式,如a=b+2

double m_dValue; //变量值 如10,表a=10

public:

CVar();

virtual ~CVar();

void InitVar();

};

class CVarList

{

public:

list<CVar*> m_VarList;

CVarList();

virtual ~CVarList();

bool AddVar(CVar* pVar);

};

class CExpression

{

public:

double m_dResult;

char* m_strExp;

CVarList m_VarList;

bool m_bDegUnit; // 缺省采用角度单位

protected:

int m_iErrFlag; //标记表达式计算是否出错0:正常,1:表达式空2:非法变量或函数3:括号不匹配

int m_iFunFlag; //标记当前正在进行函数参数计算.

int m_iMatchFlag; //标记括号是否匹配

char m_cTokenType; //标记符号的类型,如分格符,变量等

char m_strToken[80];

public:

void Message(const char * strMsg);

CExpression();

virtual ~CExpression();

bool CalExp();

bool UpdateSlaveVar();

protected:

bool GetToken();

void Error();

bool IsDelim(char c);

bool IsFunc(const char *fname);

bool IsWhite(char c);

bool IsInStr(char ch,char *s);

bool Level1(double *result);

bool Level2(double *result);

bool Level3(double *result);

bool Level4(double *result);

bool Level5(double *result);

bool Level6(double *result);

bool Level7(double *result);

bool GetFunIndex(const char *name,int *index);

void PutBack();

void Unary(char o,double *r);

bool Arith(char o, double *r, double *h);

bool Primitive(double *result);

bool GetVarValue( const char * n, double * result );

bool GetVarIndex( const char * name, int * index );

};

#endif // !defined(AFX_EXPRESSION_H__2578E33F_FF86_4384_A7CE_A401BAC5A010__INCLUDED_)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航