这段代码实现了一个简单的中缀表达式求值,但是存在以下问题:
对于多位数字的处理不够严谨,只能处理个位数,无法处理多位数。
在处理带小数点的数字时,会出现错误的运算结果。
如果输入的中缀表达式中含有错误的算符或括号不匹配等情况,程序无法进行错误处理。
在压入栈中时并没有进行栈满的判断。
在gettop()方法中,如果栈为空,将返回未定义的数值。
在进行除法运算时,未考虑除数为0的情况,可能会导致程序异常。
在对多个连续操作符进行处理时,可能会出现不符合预期的结果,例如"1–1"会被解释成"1+1"。
对于运算符的优先级顺序,目前仅支持加减乘除四种运算符,如果需要加入更多的运算符,需要手动修改代码
#include <iostream>
#include<stack>
#include<map>
using namespace std;
int op(int a1, int a2, char a);//原神怎么你了
int op(int a1, int a2, char a)
{
if (a == '+')
return a1 + a2;
if (a == '-')
return a1 - a2;
if (a == '*')
return a1 * a2;
if (a == '/')
return a1 / a2;
return 0;
}
/*
* 中缀表达式求值
* 算法思路:分两个栈 算数栈 算符栈 从左到右依次扫描 算数存在算数栈里 算符存到算符栈里 若算符栈不为空则需要比较下
* 比较级 比算符栈大的直接进 小的需要先弹出 栈里的算符 在弹出 算术栈里的 两个操作数 进行运算完 存进 算数栈里后
* 再存进算符栈
*/
int main()
{
stack<int>s1;//算数栈
stack<int>s2;//算符栈
map<int, int> m;//通过映射建立比较级
m['+'] = 1;
m['-'] = 1;
m['*'] = 2;
m['/'] = 2;
m['('] = 0;//括号优先级定最低不然运算符比较会导致x(y 返回错误的值
char a[1000];
cin >> a;
for (auto e : a)
{
if (e == '\0' || e == '\n') break;//读取到空字符就跳出 不然会造成内存错误
if (e >= '0' && e <= '9')
{
s1.push(atoi(&e));//将字符转换成整形
}
else if (s2.size()==0 || m[e] > m[s2.top()] || e == '(')
{
s2.push(e);
}
else if (e == ')')
{
while (s2.top() != '(')
{
int a1 = s1.top(); s1.pop();
int a2 = s1.top(); s1.pop();
s1.push(op(a2, a1, s2.top()));
s2.pop();
}
s2.pop();
}
else if (s2.size()>0&&m[s2.top()] >= m[e])
{
int a1 = s1.top(); s1.pop();
int a2 = s1.top(); s1.pop();
s1.push(op(a2, a1, s2.top()));
s2.pop();
s2.push(e);
}
}
while (s2.size())//在整个扫描一遍后我们把剩下的处理下
{
int a1 = s1.top(); s1.pop();
int a2 = s1.top(); s1.pop();
s1.push(op(a2, a1, s2.top()));
s2.pop();
}
cout << s1.top();
}