标签:
2 1.000+2/4= ((1+2)*5+1)/4=
1.50 4.00
题解:
求后缀表达式,用后缀表达式,求解;
代码:
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<queue> #include<stack> using namespace std; const int INF=0x3f3f3f3f; #define mem(x,y) memset(x,y,sizeof(x)) #define SI(x) scanf("%d",&x) #define PI(x) printf("%d",x) typedef long long LL; const int MAXN=1010; char s[MAXN]; char work(char a,char b){ if(a==‘+‘||a==‘-‘){ if(b==‘*‘||b==‘/‘||b==‘(‘)return ‘<‘; else return ‘>‘; } if(a==‘*‘||a==‘/‘){ if(b==‘(‘)return ‘<‘; else return ‘>‘; } if(a==‘(‘&&b==‘)‘)return ‘=‘; if(a==‘#‘||a==‘(‘)return ‘<‘; return ‘>‘; } int main(){ int T; SI(T); while(T--){ double temp,p,a,b; scanf("%s",s); stack<char>S; stack<double>s2; S.push(‘#‘); for(int i=0;s[i];){ if(s[i]==‘=‘)break; if(isdigit(s[i])||s[i]==‘.‘){ temp=0,p=10; while(isdigit(s[i])||s[i]==‘.‘){ if(s[i]==‘.‘){ p=0.1; i++; continue; } if(p==10)temp=temp*p+s[i]-‘0‘; else temp=temp+(s[i]-‘0‘)*p,p*=0.1; i++; } s2.push(temp); } //s2.push(s[i++]); else{ switch(work(S.top(),s[i])){ case ‘<‘: S.push(s[i]); i++; break; case ‘>‘: // printf("%c",S.top()); if(S.top()==‘+‘||S.top()==‘-‘||S.top()==‘*‘||S.top()==‘/‘){ a=s2.top(); s2.pop(); b=s2.top(); s2.pop(); if(S.top()==‘+‘) s2.push(a+b); else if(S.top()==‘-‘) s2.push(a-b); else if(S.top()==‘*‘) s2.push(a*b); else s2.push(a/b); } S.pop(); break; case ‘=‘: S.pop(); i++; break; } } } //printf("%d %d %lf\n",S.size(),s2.size(),s2.top()); while(S.size()>1){ a=s2.top(); s2.pop(); b=s2.top(); s2.pop(); //printf("%c %lf %lf\n",S.top(),a,b); if(S.top()==‘+‘) s2.push(a+b); else if(S.top()==‘-‘) s2.push(b-a); else if(S.top()==‘*‘) s2.push(a*b); else s2.push(b/a); S.pop(); } printf("%.2lf\n",s2.top()); } return 0; }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/5236531.html