核心算法思想:
1.运用两个栈,一个存运算符,一个存数值
2.以’#‘做为标志位,开头或者结尾
3.检查当前字符,若当前字符为数值,则加入数值栈,若为运算符,则检验当前运算符的优先级,
1)若当前运算符优先级大于栈顶优先级,则把该运算符压入栈
2)若当前运算符优先级等于栈顶优先级(括号的情况),则弹出当前栈顶运算符
3)若当前预算符的优先级小于栈顶优先级,则弹出当前运算符栈顶元素,以及数据栈的两个栈顶元素,进行运算,并把运算后的值存入数据栈中
4.循环进行直到运算符栈顶元素等于当前字符
算符间的优先关系如下表所示:
直接上代码,代码中有注释(注意结尾要以#结尾)
#include <iostream>
#include <stack>
#include <map>
using namespace std;
//该全局变量存放的是所以操作符排序,目的是得知其下标,可以找出相应的优先级
map<char,int> _mapOperator{
{'+',0},
{'-',1},
{'*',2},
{'/',3},
{'(',4},
{')',5},
{'#',6}
};
double Calculation(double a,double b, char op) //计算相应的加减乘除
{
switch (op) {
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
default:
break;
}
}
char getPriority(char oper1, char oper2) //获取oper1与oper2之间的优先级
{
const char priority[][7] = //算符间的优先级关系
{
{ '>','>','<','<','<','>','>' },
{ '>','>','<','<','<','>','>' },
{ '>','>','>','>','<','>','>' },
{ '>','>','>','>','<','>','>' },
{ '<','<','<','<','<','=','0' },
{ '>','>','>','>','0','>','>' },
{ '<','<','<','<','<','0','=' },
};
int index1 = _mapOperator[oper1];
int index2 = _mapOperator[oper2];
return priority[index1][index2];
}
/*
算法思想:
1.运用两个栈,一个存运算符,一个存数值
2.以’#‘做为标志位,开头或者结尾
3.检查当前字符,若当前字符为数值,则加入数值栈,若为运算符,则检验当前运算符的优先级,
1)若当前运算符优先级大于栈顶优先级,则把该运算符压入栈
2)若当前运算符优先级等于栈顶优先级(括号的情况),则弹出当前栈顶运算符
3)若当前预算符的优先级小于栈顶优先级,则弹出当前运算符栈顶元素,以及数据栈的两个栈顶元素,进行运算,并把运算后的值存入数据栈
中
4.循环进行直到运算符栈顶元素等于当前字符
*/
double result(string &expression) //核心代码
{
stack<char> oper;
stack<double> expre;
int counter=0;
oper.push('#');
int i=0;
while (expression[i] != '#' || oper.top() !='#') {
char ch=expression[i];
if(isdigit(ch)) //判断是否为数值
{
if(counter==1) //数值的合并
{
double value = expre.top();
expre.pop();
expre.push(value*10+(ch-'0'));
counter=1;
}else
{
expre.push(ch-'0');
counter++;
}
i++;
}else
{
counter=0;
switch (getPriority(oper.top(),ch))
{
case '<':
oper.push(ch);
i++;
break;
case '=':
oper.pop();
i++;
break;
case '>':
char op = oper.top();//取得运算符
oper.pop();//弹出
double a=expre.top();//取得数值1,以下类似
expre.pop();
double b=expre.top();
expre.pop();
expre.push(Calculation(b,a,op));
break;
}
}
}
return expre.top();
}
int main()
{
string expression;
cin >> expression;//读取一个字符串
cout<<expression<<": "<<result(expression)<<endl;
return 0;
}
结果展示