按照中缀转成后缀进行计算的,每次遇到优先级高的就弹出进行计算再压入栈中,在实际测试的时候,发现总是会优先匹配小括号再去匹配中括号和大括号,所以这三个的优先级大小不存在区别,这样的话就可以直接使用之前的表达式计算去做了
#include<iostream>
#include<stack>
using namespace std;
char str[1005];
stack<double> num;
stack<char> opt;
int flag=1;
bool isOperator(char ch){
if(ch=='+'||ch=='-'||ch=='*'||ch=='/') return true;
else return false;
}
int getPriority(char ch){
int level=0;
switch(ch){
case '(':
case '[':
case '{':
level=1;
break;
case '+':
case '-':
level=2;
break;
case '*':
case '/':
level=3;
break;
default:
break;
}
return level;
}
void cal(char c){
double a=num.top();
num.pop();
double b=num.top();
num.pop();
if(c=='+'){
num.push(a+b);
}else if(c=='-'){
num.push(b-a);
}else if(c=='*'){
num.push(a*b);
}else if(c=='/'){
num.push(b/a);
}
}
int main(){
while(cin>>str){
int i=0;
flag=1;
if(str[0]=='-'){
flag=-1;
i++;
}
while(str[i]!=0){
//如果是数字
if(str[i]>='0'&&str[i]<='9'){
double tmp=0;
do{
tmp=tmp*10+str[i]-'0';
i++;
}while(str[i]>='0'&&str[i]<='9');
if(flag==-1){
tmp=tmp*flag;
flag=1;
}
num.push(tmp);
}else if(str[i]=='('||str[i]=='['||str[i]=='{'){
opt.push(str[i]);
i++;
if(str[i]=='-'){
flag=-1;
i++;
}
}else if(isOperator(str[i])){
if(opt.empty()){
opt.push(str[i]);
i++;
}else{
while(!opt.empty()){
int c=opt.top();
if(getPriority(str[i])<=getPriority(c)){
cal(c);
opt.pop();
}else{
break;
}
}
opt.push(str[i]);
i++;
}
}else if(str[i]==')'){
while(opt.top()!='('){
char c=opt.top();
opt.pop();
cal(c);
}
opt.pop();
i++;
}else if(str[i]==']'){
while(opt.top()!='['){
char c=opt.top();
opt.pop();
cal(c);
}
opt.pop();
i++;
}else if(str[i]=='}'){
while(opt.top()!='{'){
char c=opt.top();
opt.pop();
cal(c);
}
opt.pop();
i++;
}else{
i++;
}
}
while(!opt.empty()){
cal(opt.top());
opt.pop();
}
printf("%g",num.top());
}
return 0;
} 
京公网安备 11010502036488号