Portal
sample:
+ + 2 * 3 - 7 4 / 8 4 //13.0
/ -25 + * - 2 3 4 / 8 4 //12.5
/ 5 + * - 2 3 4 / 8 2 //ERROR
+10.23 //10.2
Ideas :
After adjusting for a whole day, I finally got it out.
#include<iostream>
using namespace std;//把[+-*/]用特殊的数据(测试案例中不会出现的数据)指代
#define jia 0x3f3f
#define jian -0x3f3f
#define cheng 0xffff
#define chu -0xffff
double stk[50];
int cnt;//cnt是stk[]的有效长度
double exp()
{
if(stk[0]!=jia&&stk[0]!=cheng&&stk[0]!=jian&&stk[0]!=chu) return stk[0];
else
{
for(int i=0;i<cnt-2;i++)
{
if(stk[i]==jia||stk[i]==jian||stk[i]==cheng||stk[i]==chu)
if(stk[i+1]!=jia&&stk[i+1]!=cheng&&stk[i+1]!=jian&&stk[i+1]!=chu)
if(stk[i+2]!=jia&&stk[i+2]!=cheng&&stk[i+2]!=jian&&stk[i+2]!=chu)
{
if(stk[i]==jia)
stk[i]=stk[i+1]+stk[i+2];
if(stk[i]==jian)
stk[i]=stk[i+1]-stk[i+2];
if(stk[i]==cheng)
stk[i]=stk[i+1]*stk[i+2];
if(stk[i]==chu)
{
if(stk[i+2]) stk[i]=stk[i+1]/stk[i+2];
else return 0;//如果除数为0,会返回一个inf.
}
for(int j=i+1;j<cnt-2;j++)//把已经处理过的数据覆盖掉(或者使用链表的思想,就不用费力的循环)
stk[j]=stk[j+2];
}
}
return exp();
}
}
int main()
{
char t[10];//t的规模稍微开大一点,否则容易越界
while(~scanf("%s",t))
{
if(atof(t)) stk[cnt++]=atof(t);
else if(t[0]=='*') stk[cnt++]=cheng;
else if(t[0]=='/') stk[cnt++]=chu;
else if(t[0]=='+') stk[cnt++]=jia;
else if(t[0]=='-') stk[cnt++]=jian;
}
double ans=exp();
printf(ans?"%.1lf\n":"ERROR",ans);
}
Optimized
#include<iostream>
using namespace std;
#define error 0x3f3f3f3f
double exp()//abbr of exprssion
{
string f;
cin>>f;
if(atof(f.c_str())) return stof(f);
else if(f[0]=='+')return exp()+exp();
else if(f[0]=='-')return exp()-exp();
else if(f[0]=='*')return exp()*exp();
else if(f[0]=='/')//除法情况会出现除数为0的情况 需要特判一下
{
double t1=exp(),t2=exp();
if(!t2)return error;
else return t1*1.0/t2;
}
}
int main()
{
double ans=exp();
printf(ans==error?"ERROR":"%.1lf",ans);
}