#include <iostream>
#include <string>
#include <stack>
using namespace std;
//中缀表达式转后缀表达式
string inFixToPostFix(string expr)
{
stack<char> opt; //操作符栈
string res = "";
int len = expr.size();
for (int i = 0; i < len; i++)
{
if (isdigit(expr[i])) //数字,直接保存到结果
{
res += expr[i];
}
else
{
if (i && isdigit(expr[i-1]))
{
res += ";"; //用;分割操作数和操作符
}
if (opt.empty()) //如果栈是空,操作符直接入栈
{
opt.push(expr[i]);
}
else
{
if (expr[i] == '(') //如果是左括号,直接入栈
{
opt.push(expr[i]);
}
else if (expr[i] == '*' || expr[i] == '/') //*,/优先级比较高,所以只有*,、本身出栈
{
while (!opt.empty() && (opt.top() == '*' || opt.top() == '/'))
{
res += opt.top();
res += ";";
opt.pop();
}
opt.push(expr[i]);
}
else if (expr[i] == ')') //如果是右括号,左括号之后的出栈并保存到结果
{
while (opt.top() != '(')
{
res += opt.top();
res += ";";
opt.pop();
}
opt.pop(); //左括号出栈,不保存
}
else
{
while (!opt.empty() && opt.top() != '(') //如果是+,-,除了左括号都要出栈并保存结果,因为+,-优先级低
{
res += opt.top();
res += ";";
opt.pop();
}
opt.push(expr[i]); //+,-运算符入栈
}
}
}
}
while(!opt.empty()) //栈不为空,剩下的操作符出栈
{
res += ";";
res += opt.top();
opt.pop();
}
return res;
}
//后缀表达式计算
int evalPostFix(string expr)
{
int res = 0;
stack<int> opr; //操作数栈
int len = expr.size();
int i, j;
for (i = 0; i < len; i++)
{
if (expr[i] == ';') //;的作用是分割,直接过滤
{
continue;
}
else if (isdigit(expr[i])) //遇到数字,往后查看,计算数值,入栈
{
int num = 0;
for (j = i; expr[j] != ';'; j++)
{
num = num * 10 + expr[j] - '0';
}
opr.push(num);
i = j; //这里之所以不是用i = ++j来跳过;,是因为第一层for循环中i++了
}
else //遇到操作符,从栈中弹出两个数,计算结果,把结果入栈
{
int right = opr.top();
opr.pop();
int left = opr.top();
opr.pop();
int t;
switch(expr[i])
{
case '+':
t = left + right;
opr.push(t);
break;
case '-':
t = left - right;
opr.push(t);
break;
case '*':
t = left * right;
opr.push(t);
break;
case '/':
t = left / right;
opr.push(t);
break;
}
}
}
res = opr.top(); //最后,栈中保存的就是表达式计算结果
return res;
}
//测试算法
void test()
{
string infix = "90+(30-20)*3+10/2";
int res = 90 + (30 - 20) * 3 + 10 / 2;
cout << inFixToPostFix(infix) << endl;
int cal = evalPostFix(inFixToPostFix(infix));
cout << "res: " << res << " cal: " << cal << endl;
if (res == cal)
{
cout << "right!\n";
}
else
{
cout << "wrong!\n";
}
}
int main()
{
test();
return 0;
}
表达式计算的代码实现,按照前面两篇文章的逻辑步骤实现
最新推荐文章于 2021-02-25 17:47:59 发布