#include <bits/stdc++.h>
using namespace std;
stack<char> s;
stack<double> ans;
double returncal(double x1,double x2,char c);
void newpush()
{
double x1 = ans.top();
ans.pop();
double x2 = ans.top();
ans.pop();
ans.push(returncal(x1,x2,s.top()));
s.pop();
}
double returncal(double x1,double x2,char c)
{
double x;
if(c=='+'){
x = x1 + x2;
}
else if(c=='-'){
x = x2 - x1;
}
else if(c=='*'){
x = x1 * x2;
}
else if(c=='/'){
x = x2 / x1;
}
else if(c=='^'){
x = pow(x2,x1);
}
return x;
}
int main()
{
int q,w = 0;
char str[1010];
double cnt = 0;
scanf("%s",str+1);
int len = strlen(str+1);
str[0] = '(';
str[len] = ')';
for (int i = 0; i <= len; i++){
if (str[i] == '(') {
s.push(str[i]);
}
else if (isdigit(str[i])){
cnt=0;
w=0,q=0;
while (isdigit(str[i])||str[i]=='.'){
if (str[i] == '.'){
w = 1;
q = i;
}
else cnt=cnt*10+str[i]-'0';
i++;
}
i--;
if(w==1) ans.push(cnt/pow(10,i-q));
else {
ans.push(cnt);
}
}
else if (str[i] == '+' || str[i] == '-'){
while (s.top() != '('){
newpush();
}
s.push(str[i]);
}
else if (str[i] == '*' || str[i] == '/'){
char Operator=s.top();
if (Operator == '*'||Operator == '/'||Operator == '^'){
newpush();
if(Operator == '^'&&s.top()=='/')
newpush();
}
s.push(str[i]);
}
else if (str[i] == '^'){
if (s.top() == '^')
newpush();
s.push(str[i]);
}
else if (str[i] == ')'){
while (s.top()!= '(') newpush();
s.pop();
}
}
double answer=ans.top();
if(answer-(long long)answer<1e-15)printf("%.0lf\n", ans.top());
else printf("%.5lf\n", ans.top());
return 0;
}
中国石油大学华东数据结构实验四
最新推荐文章于 2022-12-09 23:41:28 发布