四则表达式求值

将后缀表达式进行运算得出结果

#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;

stack<char>s1;
stack<int>s2;
string target;
string t;

bool det(char a){
if(s1.empty())
return false;
else{
if((s1.top()=='*'||s1.top()=='/') && (a=='+' || a == '-' || a=='('))
return true;
else return false;
}
}
void cal1(string tar){
int flag=0;
for(int i=0;i<tar.size();i++){
if(flag == 1){
flag = !flag;
continue;
}
if(isdigit(tar[i]) && isdigit(tar[i+1])){
t +=tar[i];
t +=tar[i+1];
t+= ' ';
flag = !flag;
continue;
}
if(isdigit(tar[i])){
t+=tar[i];t+=' ';}
else if(tar[i] == '*' || tar[i] == '/')
s1.push(tar[i]);
else if(tar[i]=='(' || tar[i] == '+' || tar[i] == '-'){
if(det(tar[i]))
while(s1.top()=='*' ||s1.top()=='/'){
t+=s1.top();
t+=' ';
s1.pop();
}
s1.push(tar[i]);
}
else if(tar[i] == ')'){
while(s1.top()!='('){
t+=s1.top();
t+=' ';
s1.pop();
}
s1.pop();
}
}
while(!s1.empty()){
t+=s1.top();
t+=' ';
s1.pop();
}
}
//从左到右遍历后缀表达式的每个数字和符号，遇到是数字就进栈，遇到是符号就将处于栈顶的两个数字出栈，进行运算，运算结果进栈，一直到获得结果。
int cal3(int a,int b,char c){
if(c == '+')
return a+b;
else if(c == '-')
return a-b;
else if(c== '*')
return a*b;
else
return a/b;
}
int cal2(){
int a,b;
string temp;
stringstream ss;
int flag = 0;

for(int i=0;i<t.size();i++){
if(flag == 1){
flag = !flag;
continue;
}
if(t[i]==' ')
continue;
if(isdigit(t[i]) && isdigit(t[i+1])){
temp+=t[i];
temp+=t[i+1];
ss << temp;
ss >> a;
s2.push(a);
flag = !flag;
continue;
}
if(isdigit(t[i])){
s2.push(t[i]-'0');
}
else{
a = s2.top();
s2.pop();
b = s2.top();
s2.pop();
a = cal3(b,a,t[i]);
s2.push(a);
}
}
return s2.top();
}

int main(){
cin >> target;
cal1(target);
cout << cal2() << endl;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120