看到别人写的一个表达式求值程序,想到很久之前写的一个。中间有个字符串转数值型,可以用stringstream来实现或者c语言里面的strtod直接得到
#include<iostream>
#include<string>
#include<cmath>
#include<stack>
#include<vector>
using namespace std;
class Data{
public:
double value;
bool is_fuhao;
int priority;
char fuhao;
Data():is_fuhao(false){}
};
double get_value(string str){
if(str.length()==1)
return (int)str[0]-(int)'0';
int int_part=0;
double doub_part=0;
string::size_type i=0;
for(;i<str.length()&&str[i]!='.';++i)
int_part=10*int_part+(int)str[i]-(int)'0';
if(i!=str.length()){
string s1(str,i+1,str.length()-i-1);
double m=get_value(s1);
doub_part=m/pow(10.0,(int)s1.length());
}
return int_part+doub_part;
}
int main(){
string s;
while(cin>>s){
vector<Data> vdata;
vector<Data> hou_zui;
stack<Data> temp_stack;
stack<double> result;
for(string::size_type i=0;i!=s.length();){
Data m_data;
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='('||s[i]==')'){
m_data.is_fuhao=true;
m_data.fuhao=s[i];
if(s[i]=='+'||s[i]=='-')
m_data.priority=1;
else if(s[i]=='('||s[i]==')')
m_data.priority=0;
else
m_data.priority=2;
++i;
}
else{
string::size_type flag=i,len=1;
++i;
if(i!=s.length()){
while(s[i]!='+'&&s[i]!='-'&&s[i]!='*'&&s[i]!='/'&&s[i]!='('&&s[i]!=')'){
++len;
++i;
if(i==s.length())
break;
}
string s_temp(s,flag,len);
m_data.value=get_value(s_temp);
}
else
m_data.value=s[flag]-'0';
}
vdata.push_back(m_data);
}
bool flag=true;
for(vector<Data>::iterator i=vdata.begin();i!=vdata.end();++i){
if(!i->is_fuhao)//如果不是符号
hou_zui.push_back(*i);
else{
if(temp_stack.empty()||i->fuhao=='(')
temp_stack.push(*i);
else{
if(i->priority<=temp_stack.top().priority&&i->fuhao!=')'){
while(temp_stack.top().priority>=i->priority){
hou_zui.push_back(temp_stack.top());
//cout<<temp_stack.top().fuhao<<endl;
temp_stack.pop();
if(temp_stack.empty())
break;
}
temp_stack.push(*i);
}
else if(i->fuhao==')'){
while(temp_stack.top().fuhao!='('){
hou_zui.push_back(temp_stack.top());
temp_stack.pop();
}
temp_stack.pop();
}
else{
temp_stack.push(*i);
}
}
}
}
while(!temp_stack.empty()){
hou_zui.push_back(temp_stack.top());
temp_stack.pop();
}
for(vector<Data>::iterator i=hou_zui.begin();i!=hou_zui.end();++i){
if(!i->is_fuhao)
result.push(i->value);
else{
if(i->fuhao=='+'){
double a,b;
a=result.top();
result.pop();
b=result.top();
result.pop();
result.push(b+a);
}
else if(i->fuhao=='-'){
double a,b;
a=result.top();
result.pop();
b=result.top();
result.pop();
result.push(b-a);
}
else if(i->fuhao=='*'){
double a,b;
a=result.top();
result.pop();
b=result.top();
result.pop();
result.push(b*a);
}
else{
double a,b;
a=result.top();
result.pop();
b=result.top();
result.pop();
result.push(b/a);
}
}
}
cout<<result.top()<<endl;
}
return 0;
}