满足运算符 + - * / ()
运算数 负数,小数,整数
//中缀转后缀,并求值
/*
此过程一共分为2步:
1.将中缀转化为后缀:
*遇见运算数直接加入数组,运算符入栈,判断栈顶运算符和遍历的运算符优先级,如果栈顶运算符大于等于此运算符,则运算符出栈加入数组
2.后缀表达式求值
*遇见运算数直接入栈,遇见运算符则最前面的2个运算数出战,计算结果,并入栈
3.整合在一起:一共设定2个栈,一个运算数栈,一个运算符栈,遇见运算数直接入栈,遇见有运算符出栈,则出栈2个运算数,并将结果入栈。
*/
#include <stack>
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <sstream> //使用stringstream需要引入这个头文件
using namespace std;
//vector<string> arrays;//后缀表达式数组
stack<double> operandS; //运算数栈
map<char, int> priority;//运算符优先级
string operators = "*+-/()"; //运算符
//模板函数:将string类型变量转换为常用的数值类型(此方法具有普遍适用性)
template <class Type>
Type stringToNum(const string& str)
{
istringstream iss(str); //先把string输入流
Type num;
iss >> num; //再把流输出到type
return num;
}
double value(double d1, double d2, char c)
{
switch (c)
{
case '+':
return d1 + d2;
break;
case '-':
return d1 - d2;
break;
case '*':
return d1 * d2;
break;
case '/':
return d1 / d2;
break;
default:
break;
}
}
void trans(string str) {
stack<char> operatorS; //运算符栈
operatorS.push('#'); //栈底设为#
string tmpStr;
double d1;
double d2;
double c;
for (int i = 0; i < str.size(); i++)
{
//运算数
//1.正常数字
//2.带有正负号的数字(前一个字符必定是运算符)
if (isdigit(str[i]) || ((str[i] == '+' || str[i] == '-') && (i==0 || string("*+-/(").find(str[i-1]) != string::npos)))
{
tmpStr = str[i] != '+' ? str.substr(i, 1) : "";
while (i+1<str.size() && operators.find(str[i+1]) == string::npos) //下一个字符不是符号,将其连起来
{
tmpStr += str[++i];
}
operandS.push(stringToNum<double>(tmpStr));
}
//运算符
else
{
if (str[i] == '(') //直接进栈
{
operatorS.push(str[i]);
}
else
{
if (str[i] == ')')
{
while (operatorS.top() != '(')
{
d2 = (operandS.top());
operandS.pop();
d1 = operandS.top();
operandS.pop();
c = operatorS.top();
operatorS.pop();
operandS.push(value(d1, d2, c));
}
operatorS.pop();
}
else
{
while (priority[str[i]] <= priority[operatorS.top()])
{
d2 = operandS.top();
operandS.pop();
d1 = operandS.top();
operandS.pop();
c = operatorS.top();
operatorS.pop();
operandS.push(value(d1, d2, c));
}
operatorS.push(str[i]);
}
}
}
}
while (operatorS.size() > 1)
{
if (operatorS.top()!='#')
{
d2 = operandS.top();
operandS.pop();
d1 = operandS.top();
operandS.pop();
c = operatorS.top();
operatorS.pop();
operandS.push(value(d1, d2, c));
}
}
}
int main()
{
priority['*'] = priority['/'] = 3;
priority['+'] = priority['-'] = 2;
priority['('] = 1;
priority['#'] = 0;
string str;
getline(cin, str);
trans(str);
cout << "最终结果:" << operandS.top() << endl;
return 0;
}