标签:return clu while pac head ack cas ase static
#ifndef __CALCULATIONFORMULA_HEAD__ #define __CALCULATIONFORMULA_HEAD__ #include <iostream> #include <stack> #include <cstdio> #include <string> #include <cstdio> using namespace std; class CalculatiomFormula { public: CalculatiomFormula(string _formula) { s1 = _formula+"="; s2 = ""; } //得到结果 static double getValueByStr(string _formula) { CalculatiomFormula* pCalculatiomFormula = new CalculatiomFormula(_formula); pCalculatiomFormula->deal(); double reslut = pCalculatiomFormula->countt(); return reslut; } private: string s1,s2; stack<char> s; stack<double> c; public: void init() { while(!s.empty()) s.pop(); while(!c.empty()) c.pop(); } int pro(char ch) { switch(ch) { case ‘+‘: case ‘-‘:return 1; case ‘*‘: case ‘/‘:return 2; default :return 0; } } void deal() { init(); int i=0,len=s1.length(); s.push(‘#‘); while(i<len-1) { if(s1[i]==‘(‘) s.push(s1[i++]); else if(s1[i]==‘)‘) { while(s.top()!=‘(‘) { s2+=s.top(); s2+=‘ ‘; s.pop(); } s.pop(); i++; } else if(s1[i]==‘+‘||s1[i]==‘-‘||s1[i]==‘*‘||s1[i]==‘/‘) { while(pro(s.top())>=pro(s1[i])) { s2+=s.top(); s2+=‘ ‘; s.pop(); } s.push(s1[i]); i++; } else { while(s1[i]<=‘9‘ && s1[i]>=‘0‘||s1[i]==‘.‘) s2+=s1[i++]; s2+=‘ ‘; } } while(s.top()!=‘#‘) { s2+=s.top(); s.pop(); s2+=‘ ‘; } } double countt() { int len=s2.length(),i=0; double y,x; while(i<len) { if(s2[i]==‘ ‘) i++; else { switch(s2[i]) { case ‘+‘:x=c.top();c.pop();x+=c.top();c.pop();i++;break; case ‘-‘:x=c.top();c.pop();x=c.top()-x;c.pop();i++;break; case ‘*‘:x=c.top();c.pop();x*=c.top();c.pop();i++;break; case ‘/‘:x=c.top();c.pop();x=c.top()/x;c.pop();i++;break; default : { x=0.0; while(s2[i]<=‘9‘&&s2[i]>=‘0‘) x=x*10+(s2[i++]-‘0‘); if(s2[i]==‘.‘) { i++; double k=10.0;y=0.0; while(s2[i]<=‘9‘&&s2[i]>=‘0‘) { y+=(s2[i++]-‘0‘)/k; k*=10; } x+=y; } } } c.push(x); } } return c.top(); } }; #endif // __CALCULATIONFORMULA_HEAD__
标签:return clu while pac head ack cas ase static
原文地址:http://www.cnblogs.com/yyroom/p/7742486.html