#include<iostream>
#include<stack>
#include<cstring>
#include<cmath>
#include<cstdlib>
using namespace std;
double evalPostFix()
{
stack<double> s;
string token;
double a,b,result;
cin>>token;
while(token[0] != '=')
{
result = atof(token.c_str()); //将字符型转成浮点型
if(result != 0.0)
{
s.push(result);
}
else if(token == "0.0")
{
s.push(result);
}
else
{
switch(token[0])
{
case '+':
{
a = s.top(); s.pop(); b=s.top();
s.pop();s.push(a+b);break;
}
case '-':
{
a = s.top(); s.pop(); b=s.top();
s.pop();s.push(a-b);break;
}
case '*':
{
a = s.top(); s.pop(); b=s.top();
s.pop();s.push(a*b);break;
}
case '/':
{
a = s.top(); s.pop(); b=s.top();
s.pop();s.push(a/b);break;
}
case '^':
{
a = s.top() ;s.pop(); b=s.top();
s.pop();s.push(exp(a*log(b)));break;
}
}
}
cin>>token;
}
return s.top();
}
int main()
{
cout<<evalPostFix()<<endl;
return 0;
}
计算后缀表达式的值
最新推荐文章于 2023-11-25 22:15:35 发布