#include<iostream>
#include<stack>
#include<sstream>
using namespace std;
bool isNum(char num) {//判断当前字符是否为数字
return (num>='0'&&num<='9')?true:false;
}
int pri(char op) {//+-优先级为1,*/优先级为2
return (op=='+'||op=='-')?1:2;
}
bool cmp(char op,stack<char>st) {//判断栈顶元素与即将要压入栈的元素优先级
if(st.empty()||st.top()=='('||(pri(op)) > (pri(st.top()))) {
return true;
}else {
return false;
}
}
int strToNum(string str){//将数字字符串转换为对应的整数类型
stringstream ss;
ss<<str;
int op;
ss>>op;
return op;
}
string midToAfter(string s) //将一个中缀表达式转换为后缀表达式
stack<char>sta;
string res = "";
for(int i = 0; i < s.length();) {
if(s[i] == ' '){
i++;
continue;
}
if(isNum(s[i])) {
string temp = "";
while(isNum(s[i])) {
temp += s[i];
i++;
}
temp+='_';
res += temp;
} else {
if(s[i]=='('){
sta.push(s[i]);
}else if(s[i]!= ')') {
if(cmp(s[i],sta)) {
sta.push(s[i]);
} else {
while(!cmp(s[i],sta)) {
res += sta.top();
sta.pop();
}
sta.push(s[i]);
}
} else{
while(sta.top()!='(') {
res += sta.top();
sta.pop();
}
sta.pop();
}
i++;
}
}
while(!sta.empty()) {
res += sta.top();
sta.pop();
}
return res;
}
int jisuan(char op,int a,int b) {//计算两个数
return (op=='+') ? a+b :(op=='-')?b-a:(op=='*')?a*b:b/a;
}
int result(string s) {//计算后缀表达式
s = midToAfter(s);
stack<int>num;
int len = s.length();
if(len == 0){
return 0;
}
for(int i = 0; i < len;) {
if(isNum(s[i])) {
string str = "";
while(isNum(s[i])) {
str += s[i];
i++;
}
num.push(strToNum(str));
} else if(s[i]!='_') {
int a = num.top();
num.pop();
int b = num.top();
num.pop();
num.push(jisuan(s[i],a,b));
i++;
} else {
i++;
}
}
return num.top();
}
int main(){
string op;
cout<<"请输入一个表达式:"<<endl;
cin>>op;
cout<<result(op)<<endl;
return 0;
}
中缀转后缀并计算
最新推荐文章于 2022-10-31 09:41:05 发布