开始用想用栈模拟,结果发现很不幸对于+ + + 1 2 + 3 4 5 算不出来,考虑输入输出,考虑语法,考虑容器是否清空,考虑是不是有些情况和特殊数据没有考虑到(算法),考虑是否常识有误
#include<iostream>
#include<cstdio>
#include<stack>
#include<string>
#include<sstream>
#include<cmath>
using namespace std;
stack<string > stac;
string s1,s2;
float cal(char c,string b,string a){
float f1,f2;
stringstream ss;
ss<<b;ss>>f1;
ss.clear();
ss<<a;ss>>f2;
ss.clear();
if(c=='+')return f1+f2;
else if(c=='-')return f1-f2;
else if(c=='*')return f1*f2;
else if(c=='/')return f1/f2;
}
int main(){
getline(cin,s1);
// cout<<s1<<endl;
// cout<<" aoidfjifj"<<endl;
stringstream ss(s1);
while(ss>>s2){
// cout<<s2<<endl;
stac.push(s2);
}
ss.clear();
while(stac.size()!=1){
string a,b,c,d,e;
a=stac.top();stac.pop();
b=stac.top();stac.pop();
c=stac.top();stac.pop();
// cout<<a<<" "<<b<<" "<<c<<endl;
if(!isdigit(c[0])){
// cout<<"test"<<endl;
float f3=cal(c[0],b,a);
stringstream sss;
sss<<f3;
sss>>e;
// ss.clear();
// cout<<e<<endl;
stac.push(e);
// cout<<e<<" "<<stac.top()<<" tot1"<<endl;
}
else {
d=stac.top();stac.pop();
float f3=cal(d[0],c,b);
// cout<<"2 "<<f3<<endl;
stringstream sss;
sss<<f3;
sss>>e;
stac.push(e);
stac.push(a);
// cout<<stac.top()<<" tot2"<<endl;
}
}
float ff;
stringstream ssss(stac.top());
ssss>>ff;
stac.pop();
printf("%f\n", ff);
return 0;
}
后来看网上用的二叉树的递归:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
using namespace std;
char shz[100];
double cal(){
scanf("%s",shz);
if(shz[0]=='+')return cal()+cal();
if(shz[0]=='-')return cal()-cal();
if(shz[0]=='*')return cal()*cal();
if(shz[0]=='/')return cal()/cal();
return atof(shz);
}
int main(){
double a=cal();
printf("%f\n",a);
return 0;
}
这道题的认识:
1:stringstream ss每用完一次就要ss.clear(),否则第二次会乱七八糟;
2:string 转字符串数组用 shz.c_str();
3:变量申明的时候用double并用double计算,用float输出