-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperator.cpp
More file actions
77 lines (70 loc) · 1.82 KB
/
operator.cpp
File metadata and controls
77 lines (70 loc) · 1.82 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
#include "operator.h"
#include "complexnumber.h"
Operator::Operator(Operator::Type t_) : m_type{t_} { }
Operator::Operator(char c_) : Operator(charToType(c_)) { }
Operator::Operator(const std::string& s_) : Operator(stringToType(s_)) { }
void Operator::evaluate(Stack<ComplexNumber>& operands_) const {
ComplexNumber arg1, arg2;
switch (m_type) {
case Type::PLUS:
arg2 = operands_.pop();
arg1 = operands_.pop();
operands_.push(arg1 + arg2);
break;
case Type::MINUS:
arg2 = operands_.pop();
arg1 = operands_.pop();
operands_.push(arg1 - arg2);
break;
case Type::MULTIPLY:
arg2 = operands_.pop();
arg1 = operands_.pop();
operands_.push(arg1 * arg2);
break;
case Type::DIVIDE:
arg2 = operands_.pop();
arg1 = operands_.pop();
operands_.push(arg1 / arg2);
break;
case Type::REAL:
arg1 = operands_.pop();
operands_.push(arg1.real());
break;
case Type::IMAGINARY:
arg1 = operands_.pop();
operands_.push(ComplexNumber(0.0, arg1.imaginary()));
break;
case Type::ABS:
arg1 = operands_.pop();
operands_.push(arg1.abs());
break;
default:
break;
}
}
Operator::Type Operator::charToType(char c_) {
switch (c_) {
case '+':
return Type::PLUS;
case '-':
return Type::MINUS;
case '*':
return Type::MULTIPLY;
case '/':
return Type::DIVIDE;
case 'R':
return Type::REAL;
case 'I':
return Type::IMAGINARY;
case 'A':
return Type::ABS;
default:
return Type::NONE;
}
}
Operator::Type Operator::stringToType(const std::string& s_) {
if (s_.size() > 0) {
return charToType(s_[0]);
}
return Type::NONE;
}