<span style="font-size:18px;">toPosfix函数将中缀表达式转换为后缀表达式,calculatePosfix函数计算后缀表达式的值。
#include <iostream>
#include <stack>
#include <string>
using std::string;
using std::stack;
using std::cout;
using std::cin;
using std::endl;
string &toPosfix(string &s, string &format)
{//中缀表达式转后缀表达式,并且可以计算小数
stack<char> sta;
string numbers{ "0123456789." };
string signl{ "+-" };
string signh{ "*/" };
string numbe;//判断某数是否为多位数
bool flag = false;
for (const char &ch : s)
{
if (ch == ' ') continue;
//判断这是几位数
if (numbers.find(ch) != string::npos)
{
flag = true;
numbe.push_back(ch);
continue;
}
else if (flag)
{
flag = false;
format.insert(format.end(), numbe.begin(), numbe.end());
numbe.clear();
format.push_back(' ');
}
//判断ch什么符号
if (ch == '(') sta.push(ch);
else if (signl.find(ch) != string::npos)
{//如果进栈的是“+-”运算符
while (!sta.empty() && sta.top() != '(')
{
format.push_back(sta.top());
format.push_back(' ');
sta.pop();
}
sta.push(ch);
}
else if (signh.find(ch) != string::npos)
{
while (!sta.empty() && sta.top() != '('&&signh.find(sta.top()) != string::npos)
{
format.push_back(sta.top());
format.push_back(' ');
sta.pop();
}
sta.push(ch);
}
else if (ch == ')')
{
//ch==')'
while (!sta.empty() && sta.top() != '(')
{
format.push_back(sta.top());
format.push_back(' ');
sta.pop();
}
sta.pop();
}
}
if (!numbe.empty())
{
format.insert(format.end(), numbe.begin(), numbe.end());
numbe.clear();
format.push_back(' ');
}
while (!sta.empty())
{
format.push_back(sta.top());
format.push_back(' ');
sta.pop();
}
return format;
}
double calculatePosfix(string &s)
{
stack<double> sta;
double sum = 0;
string numbers{ "0123456789." };
string sign{ "+-*/" };
string numbe;
double num1, num2;
for (const char &ch : s)
{
if (ch == ' '&&!numbe.empty())
{
double digit = stod(numbe);
sta.push(digit);
numbe.clear();
}
if (numbers.find(ch) != string::npos)
numbe.push_back(ch);
else if (sign.find(ch) != string::npos)
{
num2 = sta.top(), sta.pop();
num1 = sta.top(), sta.pop();
double ans = 0;
switch (ch)
{
case '+':
ans += num1 + num2;
break;
case '-':
ans += num1 - num2;
break;
case '*':
ans += num1*num2;
break;
case '/':
ans += num1 / num2;
break;
}
sta.push(ans);
}
}
while (!sta.empty())
{
sum += sta.top();
sta.pop();
}
return sum;
}
double calculateinfix(string &s)
{
string format;
toPosfix(s, format);
return calculatePosfix(format);
}
int main()
{
string s{ "9.8*2+3-(2*3-6+5)" };
cout << calculateinfix(s) << endl;
cout << 9.8 * 2 + 3 - (2 * 3 - 6 + 5) << endl;
return 0;
}</span>
给定一个字符串表达式s,计算其值(使用string和stack实现)
最新推荐文章于 2022-12-05 15:35:34 发布