我们人类习惯于书写“中缀式”,如 ,其值为。 (p.s. 为什么人类习惯中缀式呢? 是因为中缀式比后缀式好用么? )
而计算机更加习惯“后缀式”(也叫“逆波兰式”,Reverse Polish Notation)。 上述中缀式对应的后缀式是:
现在,请对输入的后缀式进行求值。3 + 5 * 2
13
3 5 2 * +
输入格式:
在一行中输入一个后缀式,和之间用空格分隔,运算数长度不超过位,运算符仅有 四种。运算数
运算符
6
+ - * /
输出格式:
在一行中输出后缀式的值,保留一位小数。
输入样例:
3 5.4 2.2 * +
输出样例:
14.9
知识点1
getline导致生成的本字符串结束
(1)到文件结束,(2)遇到函数的定界符,(3)输入达到最大限度。
第一种以换行符 '\n' 结束字符串的读入。原型是 getline(std::cin,string ch)。
另外一种是以一个字符来结束字符串的读入.原型 getline(std::cin,string s,char ch),表示以字符ch来结束字符串的读入
知识点2
s.back() 返回队尾元素
s.empty() 如果队列空则返回真
s.front() 返回队首元素
s.pop() 删除队首元素
s.push() 在队尾加入一个元素
s.size() 返回队列中元素的个数
s.emplace(args) 由args构造
s.top() 返回栈顶元素
知识点3
atof把字符串转换成浮点数,所使用的头文件为<stdlib.h>
#include <bits/stdc++.h>
using namespace std;
string str;//定义一个字符串str,使用cin对字符串进行赋值,使用cout输出字符串
int n;
stack<double> s;//储存double型数据的栈
int main()
{
double num1, num2;
getline(cin, str);
n = str.size();//返回队列中元素的个数,栈的大小
for (int i = 0; i < n; i++)
{
if (str[i] == ' ')
{
continue;
}
else if ((str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') && (i == n - 1 || str[i + 1] == ' '))
{//可能存在负数的情况
num1 = s.top();//s.top()返回栈顶元素
s.pop();//s.pop()删除队首元素
num2 = s.top();
s.pop();
if (str[i] == '+')
{
s.push(num1 + num2);//s.push()在队尾加入一个元素
}
else if (str[i] == '-')
{
s.push(num2 - num1);
}
else if (str[i] == '*')
{
s.push(num1 * num2);
}
else
{
s.push(num2 / num1);
}
}
else
{
string temp = "";
while (str[i] != ' ')
{
temp += str[i];
i++;
}
num1 = atof(temp.c_str());
//atof把字符串转换成浮点数,所使用的头文件为<stdlib.h>
s.push(num1);
}
}
printf ("%.1f\n", s.top());
s.pop();
return 0;
}