C++四则运算(带负数小数,不含大数)

    科技2022-07-10  134

    思路就是定义运算符栈和操作数栈,用逆波兰式的思想完成四则运算

    细节: 1、用map标记运算符优先级,用stringstream从字符串中读取操作数

    2、stringstream可能有无法分辨字母和数字的坑,所以要加个if判断下字符串的首位是数字还是字母,就可以用stringstream来读取操作数了

    下面代码仅供参考,可能还存在很多bug和啰嗦的地方,欢迎指正

    #include <bits/stdc++.h> using namespace std; #define N 1001 map<string,int> jibie= {{"#",0},{"(",0},{")",0},{"+",1},{"-",1},{"*",2},{"/",2}}; stack<double>num; stack<string>fuhao; stringstream ss; string s; double jisuan(double n1,double n2,string s)//计算加减乘除 { if(s=="+") return n1+n2; else if(s=="-") return n1-n2; else if(s=="*") return n1*n2; else return n1/n2; } void compute()//弹出两个操作数并计算 { string op=fuhao.top(); fuhao.pop(); double n2=num.top(); num.pop(); double n1=num.top(); num.pop(); double ans=jisuan(n1,n2,op); num.push(ans); } void takenum()//提取字符串中的操作数 { double val; ss>>val; num.push(val); stringstream tmp; tmp<<val; string tmp1; tmp>>tmp1; s=s.substr(tmp1.size()); //tmp的长度即为操作数(包括负数小数)的长度,截取子串表示这个数已经读完了 } int main() { int t; cin>>t; while(t--) { cin>>s; fuhao.push("#"); ss<<s; while(s.size()!=1) { if(s[0]>'0'&&s[0]<'9') //如果为字符串首位为数字,则从字符串中读取出操作数 { takenum(); } else if(s[0]=='(') { string order; order=s.substr(0,1); fuhao.push(order); s=s.substr(1); ss.str(""); //stringstream清空并读入操作完的字符串 ss<<s; } else if(s[0]==')') { while(fuhao.top()!="(") compute(); fuhao.pop(); s=s.substr(1); } else //当字符串首位为+-*/四个运算符 { string order; order=s.substr(0,1); if(jibie[order]>jibie[fuhao.top()]) fuhao.push(order); else { compute(); fuhao.push(order); } s=s.substr(1); } ss.str(""); ss<<s; } while(fuhao.top()!="#") compute(); cout<<fixed<<setprecision(4)<<num.top()<<endl; } return 0; }

    本蒟蒻的第一条博客。。

    Processed: 0.015, SQL: 8