//整数,加,减,乘,除,多重小括号表达式的求值,例如 -1+(2-(3+4)/7)*5,(不带输入检查): #include <sstream> #include <iostream> #include <string> using namespace std; int sToI(string s); string iToS(int myInt); string sCalculate(string s1, string s2, char opr); string nobracket(string s); void main(){ int n, start=0, i; string s, s1; cout<<"Input the expression :"<<endl; cin>>s; //例如 -1+(2-(3+4)/7)*5 //处理括号: while(start != -1){ start = -1; n = s.length(); for(i=0;i<n;i++){ if(s.at(i)==‘(‘){ start = i+1; } else if(s.at(i)==‘)‘){ s1 = nobracket(s.substr(start,i-start)); //处理没有括号的子表达式 s = s.substr(0,start-1) + s1 + s.substr(i+1); //括号内的值代替原括号及其内容 // cout<<"s = "<<s<<endl; break; } } } s = nobracket(s); //处理没有括号的整个表达式 cout<<s<<endl; } string nobracket(string s){ //处理没有括号的整个表达式 int start=0, n, i, j, m=0; char c; string subS[200]; c=s.at(0); if(c==‘+‘) s.replace(0,1,""); //如果表达式最开头有正号,除去它 else if(c==‘-‘) s.replace(0,1,"_"); //如果表达式最开头有负号,用下划线代替它 n = s.length(); for(i=0;i<n;i++){ c=s.at(i); if(c==‘+‘ || c==‘-‘ || c==‘*‘ || c==‘/‘){ subS[m++]=s.substr(start,i-start); //把各个数字和运算符分别放到数组 subS[] 单元里 subS[m++]=c; start=i+1; } } subS[m]=s.substr(start); i=0; while(i<m){ c=subS[i].at(0); if(c==‘*‘ || c==‘/‘){ //先乘除 subS[i-1]=sCalculate(subS[i-1], subS[i+1], c); for(j=i;j<m-1;j++) subS[j]=subS[j+2]; m -= 2; } else i++; } for(i=1;i<m;i=i+2){ //后加减 subS[0]=sCalculate(subS[0], subS[i+1], subS[i].at(0)); } return subS[0]; } string sCalculate(string s1, string s2, char opr){ //计算两字符串得到一个字符串 if(opr==‘+‘) return iToS(sToI(s1)+sToI(s2)); else if(opr==‘-‘) return iToS(sToI(s1)-sToI(s2)); else if(opr==‘*‘) return iToS(sToI(s1)*sToI(s2)); else if(opr==‘/‘) return iToS(sToI(s1)/sToI(s2)); else return "Error opr!"; } int sToI(string s){ //字符串转为 int if(s.at(0)==‘_‘) s.replace(0,1,"-"); //恢复下划线为负号 istringstream buffer(s); int myInt; buffer>>myInt; return myInt; } string iToS(int myInt){ //int 转为字符串 ostringstream buffer; buffer<<myInt; return buffer.str(); }
时间: 2024-10-02 07:02:35