2008年11月6日星期四

C++表达式计算

又是给某人写的作业...

#include
#include
#include
#include
#include
#include
#include
using namespace std;
//栈内优先级
map isp;
//入栈优先级
map icp;
//分离表达式
list Tokenize(const string& str,const string& delimiters){
list tokens;
string::size_type delimPos = 0, tokenPos = 0, pos = 0;
if(str.length()<1) return tokens;
while(1){
delimPos = str.find_first_of(delimiters, pos);
tokenPos = str.find_first_not_of(delimiters, pos);
if(string::npos != delimPos){
if(string::npos != tokenPos){
if(tokenPos tokens.push_back(str.substr(pos,delimPos-pos));
}else{
tokens.push_back("");
}
}else{
tokens.push_back("");
}
pos = delimPos+1;
} else {
if(string::npos != tokenPos){
tokens.push_back(str.substr(pos));
} else {
tokens.push_back("");
}
break;
}
}
return tokens;
}
inline bool isNumber(char c){
return c=='.'||'0'<=c&&c<='9';
}
inline bool isSymbol(string op) {
return op=="+"||op=="-"||op=="*"||op=="/"||op=="%"||op=="^"||op=="("||op==")";
}
inline bool isSpace(char c){
return c==' '||c=='\t'||c=='\n'||c=='\r';
}
//格式化&分离表达式
list toExpressionArray(string exp){
string fexp;
const char* data = exp.data();
int idx = 0;
int len = exp.length();
for(;idx char c = data[idx];
if(isNumber(c)){
fexp.push_back(c);
}
else if(!isSpace(c)){
fexp.push_back(' ');
fexp.push_back(c);
fexp.push_back(' ');
}
}
return Tokenize(fexp," ");
}

//中序换前序
list m2l(list m) {
list l;
stack s;
string op;
string y;
s.push("#");
for(list::const_iterator i = m.begin();i!=m.end();i++){
op = *i;
if(op=="")
continue;
if(!isSymbol(op)){
l.push_back(op);
}else{
if(icp[op]>isp[s.top()]){
s.push(op);
}else if(op==")"){
y = s.top();
s.pop();
while(y!="("){
l.push_back(y);
y = s.top();
s.pop();
}
}else{
y = s.top();
s.pop();
while(icp[op] l.push_back(y);
y = s.top();
s.pop();
}
s.push(y);
s.push(op);
}//if2
}//if1
}//for
while(s.top()!="#"){
l.push_back(s.top());
s.pop();
}
return l;
}
//计算
double _calc(double o1, double o2, char op) {
switch(op){
case '+':{
return o1+o2;
}
case '-':{
return o1-o2;
}
case '*':{
return o1*o2;
}
case '/':{
return o1/o2;
}
case '^':{
return pow(o1,o2);
}
}
return 0;
}
//计算前序表达式
double calc(list in){
stack sk;
for(list::const_iterator i = in.begin();i!=in.end();i++){
string op = *i;
if(!isSymbol(op)){
sk.push(atof(op.data()));
}else{
double o2 = sk.top();
sk.pop();
double o1 = sk.top();
sk.pop();
char o = op.data()[0];
double r = _calc(o1,o2,o);
sk.push(r);
}
}
return sk.top();
}
//没用
void printList(list l){
int x=0;
for(list::const_iterator i = l.begin();i!=l.end();i++){
cout<<++x<<":"<<*i< }
}
int main()
{
isp["+"]=3;
isp["-"]=3;
isp["*"]=5;
isp["/"]=5;
isp["%"]=5;
isp["^"]=5;
isp["("]=1;
isp[")"]=6;
isp["#"]=0;

icp["+"]=2;
icp["-"]=2;
icp["*"]=4;
icp["/"]=4;
icp["%"]=4;
icp["^"]=4;
icp["("]=6;
icp[")"]=1;
icp["#"]=0;

string exp;
cout<<"Exp:";
cin>>exp;
list l1 = toExpressionArray(exp);
printList(l1);
list l2 = m2l(l1);
printList(l2);
double r = calc(l2);
cout<<"Result:"< return 0;
}

1 条评论: