Postfix expression evaluation
Feb 14, 2015 at 5:59pm UTC
Hello there!! I have to solve a postfix expression evaluation.
e.g. : 7 4 -3 * 1 5 + / *
the answer is -14
my code is always printing 55.... i need help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main(){
int i,x,y;
string a;
stack <int > b;
cin>>a;
for (i=0;i<a.size();i++){
if (a[i]!= '*' || '+' || '/' || '-' ){
b.push(a[i]);
}
else if (a[i]=='*' ){
x=b.top();
b.pop();
y=b.top();
b.pop();
a[i]=x*y;
b.push(a[i]);
}
else if (a[i]=='/' ){
x=b.top();
b.pop();
y=b.top();
b.pop();
a[i]=x/y;
b.push(a[i]);
}
else if (a[i]=='+' ){
x=b.top();
b.pop();
y=b.top();
b.pop();
a[i]=x+y;
b.push(a[i]);
}
else if (a[i]=='-' ){
x=b.top();
b.pop();
y=b.top();
b.pop();
a[i]=x-y;
b.push(a[i]);
}
}
cout<<b.top();
}
Topic archived. No new replies allowed.