7-3 后缀式求值
我们人类习惯于书写“中缀式”,如 3 + 5 * 2
,其值为13
。 (p.s. 为什么人类习惯中缀式呢?是因为中缀式比后缀式好用么?)
而计算机更加习惯“后缀式”(也叫“逆波兰式”,Reverse Polish Notation)。上述中缀式对应的后缀式是: 3 5 2 * +
现在,请对输入的后缀式进行求值。
输入格式:
在一行中输入一个后缀式,运算数
和运算符
之间用空格分隔,运算数长度不超过6
位,运算符仅有+ - * /
四种。
输出格式:
在一行中输出后缀式的值,保留一位小数。
输入样例:
3 5.4 2.2 * +
结尾无空行
输出样例:
14.9
结尾无空行
#include <stdio.h>
int main()
{
char str[10];
double st[100];
int i=0;
while(~scanf("%s", str))
{
if(str[1] == '\0' && (str[0] == '+'||str[0] == '-'||str[0] == '*'||str[0] == '/'))
{
double num1, num2, res;
num1 = st[--i];
num2 = st[--i];
switch(str[0])
{
case '+':
res = num2 + num1;
st[i++]=res;
break;
case '-':
res = num2 - num1;
st[i++]=res;
break;
case '*':
res = num2 * num1;
st[i++]=res;
break;
case '/':
res = num2 / num1;
st[i++]=res;
break;
}
}
else
{
double number;
sscanf(str, "%lf", &number);
//sscanf()会将参数str 的字符串根据参数format(格式化字符串)来转换并格式化数据, 转换后的结果存于对应的变量中。
st[i++]=number;
}
}
printf("%.1lf", st[0]);
return 0;
}
栈实现
#include <iostream>
#include <string>
#include <stack> //栈头文件
#include <iomanip>
using namespace std;
int main()
{
string str;
stack<double> s; //创建一个double栈
while (cin >> str)
{
if (str == "+" || str == "-" || str == "*" || str == "/")
{
double a, b;
a = s.top();
s.pop();
b = s.top();
s.pop();
if (str == "+")
s.push(b + a);
else if (str == "-")
s.push(b - a);
else if (str == "*")
s.push(b * a);
else
s.push(b / a);
}
else
s.push(stod(str)); //stod()将str里的元素转换为double类型
}
cout << fixed << setprecision(1) << s.top();
return 0;
}