读入一个括号化的表达式,遇到一个左括号将其入栈,遇到一个右括号将匹配括号之间的表达式出栈,然后把计算结果入栈.//相当于去括号.
[1]定义了加减乘除的基本运算.
[2]使用了把正常中缀表达式转换成前缀表达式,然后计算前缀表达式的方法.
[3]主函数主要处理括号.
#include "stack"
#include "queue"
#include "vector"
#include "string"
#include "iostream"
using namespace std;
int getpriority(string ch)
{
if (ch == "+") return 10;
if (ch == "-") return 10;
if (ch == "*") return 20;
if (ch == "/") return 20;
else
return -1;
}
stack<string> convert(const vector<string> &vec)//将s转换为前缀
{
stack<string> ans;
vector<string> oper;//存放运算符
int oldvalue = -1;
for (auto it = vec.begin(); it != vec.end();++it)
{
if (isdigit((*it)[0]))//如果it代表一个数
ans.push(*it);
else
{
int newval = getpriority(*it);
if (newval > oldvalue)
{
oper.push_back(*it);//将运算符进栈
oldvalue = newval;
}
else
{
oldvalue = newval;
while (!oper.empty()&&getpriority(oper.back())>=oldvalue)
{
ans.push(oper.back());//将运算符入进入前缀表达式
oper.pop_back();
}
oper.push_back(*it);//将运算符入栈
}
}
}
while (!oper.empty())//将剩下表达式入栈
{
ans.push(oper.back());
oper.pop_back();
}
//将结果反转
stack<string> realans;
while (!ans.empty())
{
realans.push(ans.top());
ans.pop();
}
return realans;
}
double process(const vector<string> &s)//计算前缀表达式
{
stack<string> pre = convert(s);
stack<double> var;
while (1)
{
auto it = pre.top();
if (!isdigit(it[0]))//是操作符号
{
pre.pop();//弹出运算符
auto var1 = var.top();
var.pop();
auto var2 = var.top();
var.pop();
switch (it[0])//选择操作:这里暂时只有加减乘除,所以只需一个就能存储
{
case '+': pre.push(to_string(var1 + var2)); break;
case '-': pre.push(to_string(var1 - var2)); break;
case '*': pre.push(to_string(var1 * var2)); break;
case '/': pre.push(to_string(var1 / var2)); break;
default: cerr << "error : wrong operator" << endl;
}
if (pre.size() == 1)
break;
}
else
{
var.push(stod(pre.top()));
pre.pop();
}
}
return stod(pre.top());
}
int main()
{
vector<string> s(100);
string expr;
cout << "please input the expression you want to compute :" << endl;
size_t index = 0;
cin >> expr;
for (auto ch = expr.begin(); ch != expr.end();)
{
bool preisdigit = false;
while (isdigit(*ch) || *ch == '.')
s[index].push_back(*ch++), preisdigit = true;
( preisdigit ? s[++index]:s[index] ).push_back(*ch++);
++index;
}
stack<string> S;
for (auto it = s.begin(); it != s.end();++it)
{
if (*it == "(")
S.push("(");
else if (*it == ")")
{
vector<string> temp;//用来处理括号里的表达式
while (S.top() != "(")
{
temp.push_back(S.top());
S.pop();
}
S.pop();//弹出左括号
double value = process(temp);
S.push(to_string(value));//结果入栈
}
else
S.push(*it);
}
vector<string> output;
for (; !S.empty(); S.pop())
output.insert(output.begin(), S.top());
for (auto it : output)
cout << it;
return 0;
}
“`