-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix.cpp
54 lines (53 loc) · 1.18 KB
/
postfix.cpp
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
#include<iostream>
#include<cmath>
#include<stack>
using namespace std;
float scanNum(char ch) {
int value;
value = ch;
return float(value-'0');}
int isOperator(char ch) {
if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
return 1;
return -1;
}
int isOperand(char ch) {
if(ch >= '0' && ch <= '9')
return 1;
return -1;
}
float operation(int a, int b, char op) {
if(op == '+')
return b+a;
else if(op == '-')
return b-a;
else if(op == '*')
return b*a;
else if(op == '/')
return b/a;
else if(op == '^')
return pow(b,a);
else
return INT_MIN;
}
float postfixEval(string postfix) {
int a, b;
stack<float> stk;
string::iterator it;
for(it=postfix.begin(); it!=postfix.end(); it++) {
if(isOperator(*it) != -1) {
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(operation(a, b, *it));
}else if(isOperand(*it) > 0) {
stk.push(scanNum(*it));
}
}
return stk.top();
}
int main() {
string post = "44+61/*53*+";
cout << "The result is: "<<postfixEval(post);
}