#include #include using namespace std; void compares(vector &a,vector &b,int nowsym); void calculations(vector &a,vector &b,int nowsym); int main(){ cout << "请输入一个算式,包含加减乘除乘方括号:" << endl; string s; cin >> s; vector num={"x"}; vector symbol; //1+2- -11*12/ -21^ -31( -32) -40. cout << "--------------------------------" << endl; for (auto x:s){ if(x>47&&x<58){ // 数字 if(*(num.end()-1)=="x"){ // 可以输入数字 *(num.end()-1)=to_string(x-'0'); }else{ if(symbol.end()!=symbol.begin()){ if(*(symbol.end()-1)==40){ // 有小数点 symbol.pop_back(); *(num.end()-1)=*(num.end()-1)+"."+to_string(x-'0'); }else{ *(num.end()-1)=*(num.end()-1)+to_string(x-'0'); } }else{ // 多位数字 *(num.end()-1)=*(num.end()-1)+to_string(x-'0'); } } }else{ // 符号 int sym=0; if(x=='.')sym=40; if(x=='+')sym=1; if(x=='-')sym=2; if(x=='*')sym=11; if(x=='/')sym=12; if(x=='^')sym=21; if(x=='(')sym=31; if(x==')')sym=32; if(sym==40){ // 小数点 symbol.push_back(sym); }else{ // 其他运算符 compares(num,symbol,sym); } } } // 最后一次计算 compares(num,symbol,0); cout << "计算结果为:" << *num.begin() << endl; return 0; } void compares(vector &a,vector &b,int nowsym){ // cout << "运算符" << nowsym << endl; if(b.end()==b.begin()){ // 运算符为空直接添加 b.push_back(nowsym); if(*(a.end()-1)!="x")a.push_back("x"); return; }else{ if(((*(b.end()-1)+5)(nowsym+5)){ // 新量级比较小 if(*(b.end()-1)==31){//遇到左括号( b.push_back(nowsym); a.push_back("x"); return; } calculations(a,b,nowsym); compares(a,b,nowsym); // 进行计算 }else{ if(nowsym==32){ if(*(b.end()-1)==31){ cout << "括号相遇" << endl; b.pop_back(); // a.push_back("x"); return; }else{ calculations(a,b,nowsym); compares(a,b,nowsym); } //进行计算后,不添加符号直接返回 }else{ // 同级进行计算 calculations(a,b,nowsym); compares(a,b,nowsym); } } } } void calculations(vector &a,vector &b,int nowsym){ double c1=atof((*(a.end()-1)).c_str()); double c2=atof((*(a.end()-2)).c_str()); int operation=*(b.end()-1); double value; a.pop_back(); a.pop_back(); b.pop_back(); if(operation==1){ // + value=c2+c1; }else if(operation==2){ // - value=c2-c1; }else if(operation==11){ // * value=c2*c1; }else if(operation==12){ // / value=c2/c1; }else if(operation==21){ // ^ value=pow(c2,c1); } a.push_back(to_string(value)); }