上次没做出来识别括号和小数。
// 带括号的表达式识别计算。
#include <stdio.h>
#include <iostream>
#include <stack>
#include <string>
#include <map>
#include <cmath>
using namespace std;
struct node{
double num;
char op;
bool flag;//true-操作数 false-操作码
node(double n,char c,bool f){num=n;op=c;flag=f;}
node(double n,bool f){num=n;flag=f;}
node(char c,bool f){op=c;flag=f;}
node(){}
};
stack<node> st1,st2;
map<char,int> pri;
void change(string str){
int len=str.length();
for(int i=0;i<len;i++){
node temp;
bool flag;
int e;
double num=0;
if(str[i]<='9'&&str[i]>='0'){
flag=false;e=0;
while((i<len&&str[i]<='9'&&str[i]>='0')||str[i]=='.'){
if(str[i]=='.'){
flag=true;
}else{
if(flag)
num=num+(str[i]-'0')*pow(0.1,++e);
else
num=10*num+str[i]-'0';
}
i++;
}
temp.num=num;
temp.flag=true;
st2.push(temp);
i--;
}
else{
temp.op=str[i];
temp.flag=false;
if(temp.op=='(') st1.push(temp);
else if(temp.op==')'){
while(st1.top().op!='('){
st2.push(st1.top());
st1.pop();
}
st1.pop();
}else{
while(!st1.empty()&&pri[str[i]]<pri[st1.top().op]){
st2.push(st1.top());
st1.pop();
}
st1.push(temp);
}
}
}
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
}
node calop(double a,double b,char op){
if(op=='+') return node(a+b,true);
if(op=='-') return node(a-b,true);
if(op=='*') return node(a*b,true);
if(op=='/') return node(a/b,true);
}
void cal(stack<node> res){
double ans=0;
double a,b;
char op;
stack<node> temp;
while(!res.empty()){
if(res.top().flag){
temp.push(res.top());
res.pop();
}else{
b=temp.top().num;
temp.pop();
a=temp.top().num;
temp.pop();
op=res.top().op;
res.pop();
temp.push(calop(a,b,op));
}
}
printf("\n%.2lf",temp.top().num);
}
int main(){
freopen("1.txt","r",stdin);
string arrin;
pri['(']=pri[')']=-1;
pri['*']=pri['/']=1;
pri['+']=pri['-']=0;
cin>>arrin;
cout<<arrin;
change(arrin);
stack<node> temp;
while(!st2.empty()){
if(st2.top().flag){
temp.push(st2.top());
st2.pop();
}else{
temp.push(st2.top());
st2.pop();
}
}
cal(temp);
}