-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator2.cpp
115 lines (94 loc) · 1.82 KB
/
calculator2.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include<iostream>
#include<stack>
using namespace std;
class calculator{
private:
stack<char> optr;
stack<double> opnd;
double value;
public:
calculator(){
optr.push('#');
}
void run();
void evaluate();
void clear();
private:
int lp(char op);
int rp(char op);
double operate(char theta,double a,double b);
};
double calculator::operate(char theta,double a,double b){
double ret;
switch(theta){
case '+':ret=a+b;break;
case '-':ret=a-b;break;
case '*':ret=a*b;break;
case '/':ret=a/b;break;
}
return ret;
}
int calculator::lp(char ch){
int ret;
switch(ch){
case '+':ret=3;break;
case '-':ret=3;break;
case '*':ret=5;break;
case '/':ret=5;break;
case '(':ret=1;break;
case ')':ret=6;break;
case '#':ret=1;break;
}
return ret;
}
int calculator::rp(char ch){
int ret;
switch(ch){
case '+':ret=2;break;
case '-':ret=2;break;
case '*':ret=4;break;
case '/':ret=5;break;
case '(':ret=6;break;
case ')':ret=1;break;
case '#':ret=0;break;
}
return ret;
}
void calculator::evaluate(){
char ch,op,theta;
double val,a,b;
cin>>ch;
op='#';
while((ch!='#')||(op!='#')){
if(isdigit(ch)){
cin.putback(ch);
cin>>val;
opnd.push(val);
cin>>ch;
}else if(lp(op)<rp(ch)){
optr.push(ch);
cin>>ch;
}else if(lp(op)==rp(ch)){
optr.pop();
cin>>ch;
}else{
theta=optr.top();
optr.pop();
b=opnd.top();
opnd.pop();
a=opnd.top();
opnd.pop();
opnd.push(operate(theta,a,b));
}
}
op=optr.top();
if(op!='#'){
cout<<"ÊäÈë´íÎó"<<endl;
}else{
cout<<'='<<opnd.top()<<endl<<op;
}
}
int main(){
calculator c;
c.evaluate();
}