typedef double type;
int idx;
stack<type>Sn;
type num[__];
struct Operator
{
//定義符號
static bool is(char c)
{
return c=='+' || c=='-' || c=='*'
|| c=='/' || c=='(' || c==')';
}
char o;
Operator() {}
void operator=(const char c){o=c;}
bool operator==(const char c){return o==c;}
//定義符號優(yōu)先級
bool operator<=(const Operator &b)const
{
if(o=='*' || o=='/')
return b.o=='*' || b.o=='/';
if(o=='+' || o=='-')
return b.o!='(';
if(o==')')return true;
return false;
}
//定義符號運算
type fun()
{
type x=Sn.top();Sn.pop();
type y=Sn.top();Sn.pop();
if(o=='+')return y+x;
if(o=='-')return y-x;
if(o=='*')return y*x;
if(o=='/')return y/x;
}
}op[__];
stack<Operator>So;
//讀浮點數(shù)
int read_num(int x)
{
ll fz=0,fm=0;
for(;;++x)
{
if(fm)fm*=10;
if(a[x]=='.')fm=1;
else fz=fz*10+(a[x]-'0');
if(!a[x+1] || Operator::is(a[x+1]))
break;
}
if(!fm)fm=1;
num[++idx]=fz*1.0/fm;
return x;
}
void compare(Operator c)
{
while(!So.empty() && c<=So.top())
{
if(So.top()=='('){So.pop();return;}
Sn.push(So.top().fun()),So.pop();
}
So.push(c);
}
type calculate()
{
for(int i=1;i<=idx;++i)
if(op[i]==0)Sn.push(num[i]);
else compare(op[i]);
for(;!So.empty();So.pop())
Sn.push(So.top().fun());
type res=Sn.top();Sn.pop();
return res;
}
int main()
{
sf("%s",a+1);
int n=strlen(a+1);
for(int i=1;i<=n;++i)
{
if(Operator::is(a[i]))
op[++idx]=a[i];
else i=read_num(i),op[idx]=0;
}
pf("%.2f\n",calculate());
return 0;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。