📄 expression.h
字号:
#ifndef _EXPRESSION_H
#define _EXPRESSION_H
//unit expression Parser;
/*==========================================================================*/
/* Expression Evaluator v2.0 */
/* 支持: +, -, *, /, ^, (), sin, cos, tan, asin, acos, atan, sinh, cosh, */
/* tanh, exp, ln/log, log10, sqr, trunc */
/* 11/2003 by wangjian/PHY/ZJU */
/*==========================================================================*/
#include <string>
#include <iostream>
#include <map>
#include <stack>
#include <valarray>
#include <sstream>
using namespace std;
#define MaxExpLen 4 //3.32E+或4.51E-后面允许的数字长度
#define ExpLimit 11356 //exp(num)中,num允许的最大值
typedef enum
{// + - * / ^ ( ) ; = 数字 函数
PLUS, MINUS, TIMES, DIVIDE, EXPO, OPAREN, CPAREN,SEMI, EQU, NUM, FUNC,
//标识符 结束 语句块 赋值语句 表达式 项 因子 非法符号
ID, EOL, S, A, E, T, F, BAD
}TokenTypes; //符号的类别
static char* typetable[20] ={//用于输出枚举类型
"+", "-", "*", "/", "^", "(", ")", ";", "=", "数字",
"函数", "标识符", "结束符", "S","A","E","T", "F","BAD"};
class Token
{
public:
Token(int pos,TokenTypes typ,double val,string name)
{ position = pos;
type = typ;
value = val;
str = name;
state =0;
}
Token(){};
int position; //保存单词的位置
int state; //保存单词的状态
TokenTypes type;//保存单词的类型
double value; //单词类型为数字时保存数值
string str; //单词类型为标识符或函数时保存数值
};
class Expression
{
public:
Expression(string exp):expression(exp),parseSucc(true){};//构造表达式为exp的表达式对象
Expression():parseSucc(true){};
~Expression(){
if(!tokenQue.empty()) tokenQue.clear();
if(!idMap.empty()) idMap.clear();}
public:
string getExpression(){return expression;};
void setExpression(string exp);
string getResult(void);
void setId(string idName, double val){//添加值为val,名称为idName的标识符
idMap[idName] = val;}
double getId(string idName);//得到名称为idName的标识符的值
void parse(void);//计算表达式
bool parseSucc;//标志表达式是否得到正确地计算
protected:
void lex(void);
map<string, double> idMap;//保存多个赋值语句的值
deque<Token> tokenQue;//保存词法分析产生的单词流
string expression; //保存表达式字符串
string resultStr; //表达式结果或出错信息
static int action[32][18];//LR分析表;表示在状态i时遇到各种符号时所采取的动作
};
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -