MathExpression.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Expression is a simple math expression interpreter.
  3. * expression support + - * / ^(pow) -(neg)calculate sign
  4. * expression support "()" to constrol the calculate order
  5. * the number in expression can only be the real number,don't support the scientific notation.
  6. * SetExprStr failure will break down the original expression
  7. * support 26 letter variable name(case insensitive)
  8. * use SetVar to set the variable value
  9. * the default variable value is 1
  10. * when GetResult ,if the expression is not set or the variable is not set, it will return an error code.
  11. * GetExprErrorStr get the expression error code string
  12. * GetResultErrorStr get the result error code string
  13. */
  14. namespace expInterpreter {
  15. enum AtomType{ATOM_ERROR = 0, ATOM_SYMBOL, ATOM_CONSTANT, ATOM_VARIABLE, ATOM_END};
  16. // the struct of a syntax unit, it can be a symbol, a constant or a variable
  17. typedef struct
  18. {
  19. AtomType type;
  20. union
  21. {
  22. char symbol;
  23. double constant;
  24. char variable;
  25. } value;
  26. } Atom;
  27. // read a syntax unit from the given string£¬begin at the start£¬finish at the end unit£¬return -1 if it is null.
  28. int read_atom(Atom *atom, const char *exprStr, int start);
  29. // expression
  30. class Expression
  31. {
  32. private:
  33. const static int poland_MAX;
  34. Atom *poland;
  35. int poland_N;
  36. double *var;
  37. public:
  38. Expression();
  39. ~Expression();
  40. const char* GetExprErrorStr(int err); // return the error string according to the error code
  41. const char* GetResultErrorStr(int err); // return the error string according to the error code
  42. int SetExprStr(const char *exprStr); // set the expression,generate the reverse polish notation,return 0 if succeed,error code if fail.
  43. void SetVar(char x, double value); // set the variable value
  44. int GetResult(double *result); // get the result according to the last set variable and expression,return 0 if succeed,error code if fail.
  45. const Atom *GetPoland();
  46. };
  47. }