// 后缀表达式求值 1.支持输入正整数,可输入多数位数字,如15,200等 2.表达式间隔使用空格或, 3.支持加减乘除四种运算
/*示例:
正常表达式:
3*2+15*2-9
后缀表达式:
3 2 * 15 2 * + 9 -
*/
#include <iostream>
#include <string>
#include <stack>
using namespace std;
// 判断当前字符是否为运算符
bool isoperator(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/')
{
return true;
}
else
{
return false;
}
}
// 判断当前字符是否为数字
bool isnum(char c)
{
if (c >= '0' && c <= '9')
{
return true;
}
else
{
return false;
}
}
// 获取运算符运算结果
double performoperator(char op, double num1, double num2)
{
if (op == '+')
{
return num1 + num2;
}
else if (op == '-')
{
return num1 - num2;
}
else if (op == '*')
{
return num1 * num2;
}
else if (op == '/')
{
if (num2 != 0)
{
return num1 / num2;
}
else
{
cout << "除数不能为0" << endl;
return -1;
}
}
else
{
cout << "运算符错误" << endl;
return -1;
}
}
// 后缀表达式计算
// 考虑到存在除法,使用double类型
double postfix(string exp)
{
int n = exp.length(); // 表达式长度
stack<double> S; // 用栈接收表达式中的数字,故栈的类型设为double
for (int i = 0; i < n; i++)
{
if (exp[i] == ' ' || exp[i] == ',')
{
continue;
}
else if (isnum(exp[i]))
{
double operand = 0;//设置一个操作数,实现多数位数字接收
while (i < exp.length() && isnum(exp[i]))
{
operand = (operand * 10) + (exp[i] - '0');
i++;
}
i--;
S.push(operand);
}
else if (isoperator(exp[i]))
{
// 一个小细节,这里num2是先出栈的,对于-和/运算符来说是减数/除数,需要放在performoperator参数列表中的num2位置
double num2 = S.top();
S.pop();
double num1 = S.top();
S.pop();
double res = performoperator(exp[i], num1, num2);
S.push(res);
}
}
return S.top();
}
int main()
{
string exp;
cout << "请输入:";//参考用例3 2 * 15 2 * + 9 -
//正确结果:27
getline(cin, exp);
double res = 0;
res = postfix(exp);
cout << "= " << res << endl;
cin.get();
return 0;
}
参考:
B站搬运的一位印度程序员讲解的视频:数据结构:课程导论_哔哩哔哩_bilibili
视频配套代码地址(需要梯子可访问):https://gist.github.com/mycodeschool/7702441