实现思路
先输入string类型的中缀表达式,然后转换为后缀表达式,最后感觉string类型的后缀表达式来计算值
实现代码
#include <bits/stdc++.h>
using namespace std;
stack<char> optstack;
stack<int> numstack;
int compute(string line)
{
int len = line.length();
for (int i = 0; i < len; i++)
{
char ch = line[i];
if (ch == '+')
{
int a = numstack.top();
numstack.pop();
int b = numstack.top();
numstack.pop();
numstack.push(a + b);
}
else if (ch == '-')
{
int a = numstack.top();
numstack.pop();
int b = numstack.top();
numstack.pop();
numstack.push(b - a);
}
else if (ch == '*')
{
int a = numstack.top();
numstack.pop();
int b = numstack.top();
numstack.pop();
numstack.push(a * b);
}
else if (ch == '/')
{
int a = numstack.top();
numstack.pop();
int b = numstack.top();
numstack.pop();
numstack.push(b / a);
}
//如果是数字就直接加入
else
{
numstack.push(ch - '0');
}
}
return numstack.top();
}
string toPostFix(string line)
{
string postfix;
int len = line.length();
stack<char> buffer;
for (int i = 0; i < len; i++)
{
//操作数直接输出
if (line[i] >= '0' && line[i] <= '9')
postfix.push_back(line[i]);
else
{
//若为左括号或栈为空
if (buffer.size() == 0 || line[i] == '(')
{
buffer.push(line[i]);
continue;
}
else
{
if (line[i] == ')')
{
while (buffer.size() != 0 && buffer.top() != '(')
{
postfix.push_back(buffer.top());
buffer.pop();
}
buffer.pop();
}
if (line[i] == '+' || line[i] == '-')
{
while (buffer.size() != 0 && buffer.top() != '(')
{
postfix.push_back(buffer.top());
buffer.pop();
}
buffer.push(line[i]);
}
if (line[i] == '*' || line[i] == '/')
{
while (buffer.size() != 0 && (buffer.top() == '*' || buffer.top() == '/'))
{
postfix.push_back(buffer.top());
buffer.pop();
}
buffer.push(line[i]);
}
}
}
}
while (!buffer.empty())
{
postfix.push_back(buffer.top());
buffer.pop();
}
return postfix;
}
int main()
{
string line;
cin >> line;
string postfix = toPostFix(line);
// cout << postfix << endl;
cout << compute(postfix) << endl;
}
缺陷
- 不能计算二位及以上位数的数字运算(需要对数字的位数进行判断,并用合适的集合存储)
- 没有涉及判断错误的中缀表达式
- 不能计算浮点数