switch(ch) { case print: case quit: //处理云算法,数字分组符号 case '(': case ')': case '{': case '}': case '+': case '-': case '*': case '/': case '!': case '%': //处理 let ×× = 的情况 case '=': return Token(ch); //处理数字 case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { cin.putback(ch); double val; cin>>val; return Token(number,val);
//定义variable类 class Variable { public: string name; double value; Variable(string n, double v):name(n),value(v){} };
//定义variable向量 vector<Variable> var_table;
//return the value of the Variable named s double get_value(string s) { for(int i=0; i<var_table.size(); i++) if(var_table[i].name == s) return var_table[i].value; error("get: undefined variable ",s); }
//set the Variable named s to d void set_value(string s, double d) { for(int i=0; i<var_table.size(); i++) if(var_table[i].name == s) { var_table[i].value = d; return ; } error("get: undefined variable ",s); }
double term() { double left = factorial(); Token t = ts.get();
while(true) { switch (t.kind){ case '*' : left *= factorial(); t = ts.get(); break; case '/': { double d = factorial(); if(d==0) error("divide by zero"); left/=d; t = ts.get(); break; } case '%': { int i1 = narrow_cast<int>(left); int i2 = narrow_cast<int>(factorial() ); if(i2 == 0) error("%: divide by zero"); left = i1%i2; t = ts.get(); break; } default: ts.putback(t); return left; } } }
double expression() { double left = term(); Token t = ts.get();
while(true) { switch(t.kind) { case '+': left += term(); t = ts.get(); break; case '-': left -= term(); t = ts.get(); break; default: ts.putback(t); return left; } } }
double declaration() { Token t = ts.get(); if(t.kind != name) error("name expected in declaration"); string var_name = t.name;
Token t2 = ts.get(); if(t2.kind != '=') error("= missing in declaration of ", var_name);