The classical algorithm for evaluating expressions in the data structure is to use two stacks, one memory digit and one memory operator. Each character in the expression is read sequentially, and if the number is in the number stack, the operator and the stack top operator of the operator stack compare precedence until the entire expression is evaluated. The precedence table for the operators is as follows
|
+ |
- |
* |
/ |
( |
) |
# |
| + |
> |
> |
< |
< |
< |
> |
> |
| - |
> |
> |
< |
< |
< |
> |
> |
| * |
> |
> |
> |
> |
< |
> |
> |
| / |
> |
> |
> |
> |
< |
> |
> |
| ( |
< |
< |
< |
< |
< |
= |
|
| ) |
> |
> |
> |
> |
|
> |
> |
| # |
< |
< |
< |
< |
< |
|
= |
After learning the compiling principle, it is found that recursive descent analysis can be used to find the value of an expression. The syntax of an expression is as follows
<Expr> <Term> {(+|-) <Term>}
<Term> <Factor> {(*|/) <Factor>}
<Factor> (<Expr>) | Num
According to the technique of recursive descent analysis, each non-Terminator writes a function
#pragmaOnce#include<string>using namespacestd;/************************************************************************//*The grammar is as follows <Expr> <Term> {(+|-) <Term>}<term> <Factor> {(*|/) <factor& Gt }<factor> (<Expr>) | num/************************************************************************/classcalculator{ Public: Calculator (string&str); ~Calculator (); DoubleCalculate () {returnans;} DoubleAns//the value of an expressionPrivate: intCur//the current location stringstr; Doubleexpression (); Doubleterm (); Doublefactor ();};Calculator.h
#include"Calculator.h"Calculator::calculator (string& str): str (str), cur (0), ans (0) {ans=expression ();} Calculator::~Calculator () {}Doublecalculator::expression () {DoubleNUM1 =term (); Doublenum2; while(Str[cur] = ='+'|| Str[cur] = ='-') { Charop = str[cur++];//operatornum2 =term (); if(OP = ='+') Num1 + =num2; Else if(OP = ='-') NUM1-=num2; } if(Str[cur] = =')') ++cur;//factor Encounters ' (' will call this function, so eat ') ' returnNUM1;}Doublecalculator::term () {DoubleNUM1 =factor (); Doublenum2; while(Str[cur] = ='*'|| Str[cur] = ='/') { CharOP = str[cur++] ; Num2=factor (); if(OP = ='*') NUM1 *=num2; Else if(OP = ='/') NUM1/=num2; } returnNUM1;}DoubleCalculator::factor () {CharTMP =Str[cur]; if(Cur < str.size ()-1) ++cur; if(TMP = ='(') returnexpression (); Else returnTMP-'0';}
Main function
#include <iostream>"Calculator.h"usingnamespace STD; int Main () { string str; >> str; Calculator cal (str); << cal.calculate () << Endl;}
Operation Result:
Using recursive descent analysis to find the value of an expression