-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpressions.cpp
More file actions
89 lines (80 loc) · 1.58 KB
/
expressions.cpp
File metadata and controls
89 lines (80 loc) · 1.58 KB
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
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
class Expr
{
float val;
enum KIND {ATOMIC,BINARY};
KIND kind;
Expr* left;
Expr* right;
char opr;
public:
Expr(float x)
{
val = x;
kind = ATOMIC;
}
Expr(Expr* a, char o, Expr* b)
{
left = a;
opr = o;
right = b;
kind = BINARY;
}
string toString()
{
stringstream ss;
if(kind==ATOMIC)
{
ss<<val;
}
else
{
ss<<"(";
ss<<left->toString();
ss<<opr;
ss<<right->toString();
ss<<")";
}
return ss.str();
}
float eval()
{
if(kind==ATOMIC)
{
return val;
}
else
{
if(opr=='+')
return left->eval() + right->eval();
if(opr=='-')
return left->eval() - right->eval();
if(opr=='*')
return left->eval() * right->eval();
if(opr=='/')
return left->eval() / right->eval();
}
}
};
int main(int argc, char** argv)
{
Expr A = Expr(5);
Expr B = Expr(2);
Expr C = Expr(&A,'*',&B);
cout << setprecision(2) << C.toString() << "=" << C.eval() << endl;
Expr D = Expr(4);
Expr E = Expr(&C,'/',&D);
cout << setprecision(2) << E.toString() << "=" << E.eval() << endl;
Expr one = Expr(1);
Expr two = Expr(2);
Expr three = Expr(3);
Expr four = Expr(4);
Expr EE = Expr(new Expr(&one,'+',&two),'*',new Expr(&three,'+',&four));
cout << setprecision(2) << EE.toString() << "=" << EE.eval() << endl;
Expr F = Expr(&E,'/',&EE);
cout << setprecision(2) << F.toString() << "=" << F.eval() << endl;
}