我们人类习惯于书写“中缀式”,如 3 + 5 * 2 ,其值为13。
而计算机更加习惯“后缀式”(也叫“逆波兰式”,Reverse Polish Notation)。上述中缀式对应的后缀式是: 3 5 2 * +
现在,请对输入的后缀式进行求值。
输入格式:
在一行中输入一个后缀式,运算数和运算符之间用空格分隔,运算数长度不超过6位,运算符仅有+ - * / 四种。
输出格式:
在一行中输出后缀式的值,保留一位小数。
输入样例:
3 5.4 2.2 * +
输出样例:
14.9
- #include <bits/stdc++.h>
- using namespace std;
- #define int long long
- #define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
- typedef pair<int,int> PII;
- const int N=2e6+10;
- stack <double> q;
- string s;
- signed main()
- {
- ios;
- getline(cin,s);
- for (int i=0;i<s.size();i++)
- {
- int j=i;
- while (j<s.size()&&s[j]!=' ') j++;
- string p=s.substr(i,j-i);
- if (p=="+"||p=="-"||p=="*"||p=="/")
- {
- double b=q.top();
- q.pop();
- double a=q.top();
- q.pop();
- if (p=="+") q.push(a+b);
- else if (p=="-") q.push(a-b);
- else if (p=="*") q.push(a*b);
- else q.push(a/b);
- }
- else q.push(stod(p));
- i=j;
- }
- printf("%.1lf",q.top());
- return 0;
- }