欢迎来到天天文库
浏览记录
ID:55704811
大小:20.50 KB
页数:5页
时间:2020-05-25
《小型桌面计算器源程序.doc》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、小型桌面计算器源程序#include#include#include#includeusingnamespacestd;maptable;namespaceLexer{enumToken_value{NAME,NUMBER,END,PLUS='+',MINUS='-',MUL='*',DIV='/',PRINT=';',ASSIGN='=',LP='(',RP=')'};Token_valuecurr_tok=PRINT;doublenumber_value;stringstring_value;Tok
2、en_valueget_token();}namespaceError{structZero_divide{};structSyntax_error{constchar*p;Syntax_error(constchar*q){p=q;}};}namespaceParser{doubleexpr(boolget);doubleterm(boolget);doubleprim(boolget);usingnamespaceLexer;usingnamespaceError;}namespaceDriver{intno_of_errors;std::istream*input;voidskip();
3、}Lexer::Token_valueLexer::get_token(){charch;cin>>ch;switch(ch){case'#':returncurr_tok=END;case';':case'*':case'/':case'+':case'-':case'(':case')':case'=':returncurr_tok=Token_value(ch);case'0':case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':case'.':cin.putback(ch);cin>>numbe
4、r_value;returncurr_tok=NUMBER;default:if(isalpha(ch)){cin.putback(ch);cin>>string_value;returncurr_tok=NAME;}throwError::Syntax_error("badtoken");returncurr_tok=PRINT;}}doubleParser::expr(boolget){usingnamespaceLexer;doubleleft=term(get);for(;;)switch(curr_tok){casePLUS:left+=term(true);break;caseMI
5、NUS:left-=term(true);break;default:returnleft;}}doubleParser::term(boolget){usingnamespaceLexer;doubleleft=prim(get);for(;;)switch(curr_tok){caseMUL:left*=prim(true);break;caseDIV:if(doubled=prim(true)){left/=d;break;}throwError::Zero_divide();default:returnleft;}}doubleParser::prim(boolget){usingna
6、mespaceLexer;if(get)get_token();switch(curr_tok){caseNUMBER:{doublev=number_value;get_token();returnv;}caseNAME:{double&v=table[string_value];if(get_token()==ASSIGN)v=expr(true);returnv;}caseMINUS:return-prim(true);caseLP:{doublee=expr(true);if(curr_tok!=RP)throwError::Syntax_error(")expected");get_
7、token();returne;}caseEND:return1;default:throwError::Syntax_error("primaryexpected");}}voidDriver::skip(){no_of_errors++;while(*input){charch;input->get(ch);switch(ch){case'':case';':return;}}}intma
此文档下载收益归作者所有