这是数据结构老师在课上讲的例题,具体教程可以看我上传的ppt,问题要求如下:
输入一串字符串,为十以内带括号的加减乘除,输出后缀表达式和结果。
解决思路:
先将字符串转化为后缀表达式,然后利用后缀表达式得出结果。
中缀表达式转化为后缀表达式
当中缀表达式中有括号时,
后缀表达式计算结果:
代码实现:
#include "pch.h"
#include <iostream>
#include<string>
#include<stack>
using namespace std;
int getPrior(char c)
{
switch (c)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '(':
return 3;
case ')':
return 3;
default:
return 0;
}
}
string outputString(string input)
{
string numbers = "";
stack<char> oper;
for (int i = 0; i < input.size(); i++)
{
if (input[i]=='+'||input[i]=='-'||input[i]=='*'||input[i]=='/'||input[i]=='('||input[i]==')')
{
//如果栈空,入栈
if (oper.empty())
{
oper.push(input[i]);
}
else//否则
{
if (getPrior(oper.top()) < getPrior(input[i]) || oper.top() == '(')
{
oper.push(input[i]);
if (input[i] == ')')
{
while (oper.top() != '(')
{
if (oper.top() != '('&&oper.top() != ')')
{
numbers += oper.top();
}
oper.pop();
}
oper.pop();
}
}
else
{
while (!oper.empty()&&getPrior(oper.top())>=getPrior(input[i]))
{
numbers += oper.top();
oper.pop();
}
oper.push(input[i]);
}
}
}
else
{
numbers += input[i];
}
}
while (!oper.empty())
{
numbers += oper.top();
oper.pop();
}
numbers += '\0';
return numbers;
}//得到后缀表达式
double getResult(string input)
{
stack<double> tmp;
for (int i = 0; i < input.size()-1; i++)
{
if (input[i] - '0' >= 0 && input[i] - '0' <= 9)
{
tmp.push(input[i] - '0');
}
else
{
double number2 = tmp.top();
tmp.pop();
double number1 = tmp.top();
tmp.pop();
if (input[i] == '+')
{
tmp.push(number1 + number2);
}
else if (input[i] == '-')
{
tmp.push(number1 - number2);
}
else if (input[i] == '*')
{
tmp.push(number1*number2);
}
else if (input[i] == '/')
{
tmp.push(number1 / number2);
}
}
}
return tmp.top();
}
int main()
{
cout << "请输入前缀表达式:";
string input;
cin >> input;
cout << "后缀表达式是:" << outputString(input)<<endl;
cout << "结果是:" << getResult(outputString(input))<<endl;
}
这个题可以进阶为任意数的计算,这里可以将浮点数转化为字符串,然后用stof()函数将其转化为浮点数进行运算即可。