-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.cpp
104 lines (91 loc) · 2.92 KB
/
calculator.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
#include "calculator.hpp"
std::ostream& operator<<(std::ostream& out, Calculator& calculator) {
out << calculator.getAnswer();
return out;
}
void operator<<(Calculator& calculator, const std::string& infix) {
calculator.getPostfixNotation(infix);
}
std::string Calculator::toString(const char& ch) {
std::string temp = "";
temp += ch;
return temp;
}
std::string Calculator::trimTrailingZeros(std::string str) {
if (str.find('.') != std::string::npos)
{
str = str.substr(0, str.find_last_not_of('0') + 1);
if (str.find('.') == str.size() - 1)
str = str.substr(0, str.size() - 1);
}
return str;
}
void Calculator::AC() {
postfix.empty();
instructions.empty();
}
void Calculator::getPostfixNotation(const std::string& infix) {
int i = 0;
LinkedStack<char> infixOperators;
while (i < infix.size()) {
char ch = infix[i];
if (std::isdigit(ch) || ch == '.') {
std::string temp = toString(ch);
while (i + 1 < infix.size() && (isdigit(infix[i + 1]) || infix[i + 1] == '.'))
temp += infix[++i];
postfix.push(temp);
ch = infix[i];
}
else if (ch == '(')
infixOperators.push('(');
else if (ch == ')') {
while (infixOperators.top() != '(') {
postfix.push(toString(infixOperators.top()));
infixOperators.pop();
}
infixOperators.pop();
}
else if (ch != ' ') {
while (!infixOperators.empty() && precedence[ch] <= precedence[infixOperators.top()]) {
postfix.push(toString(infixOperators.top()));
infixOperators.pop();
}
infixOperators.push(ch);
}
i++;
}
while (!infixOperators.empty()) {
postfix.push(toString(infixOperators.top()));
infixOperators.pop();
}
}
void Calculator::evaluate() {
while (!postfix.empty()) {
std::string str = postfix.top();
if (!std::isdigit(str[0])) {
double n1 = instructions.top();
instructions.pop();
double n2 = instructions.top();
instructions.pop();
if (str[0] == '+')
instructions.push(n2 + n1);
else if (str[0] == '-')
instructions.push(n2 - n1);
else if (str[0] == 'x' || str[1] == '*')
instructions.push(n2 * n1);
else if (str[0] == '/')
instructions.push(n2 / n1);
else if (str[0] == '^')
instructions.push(pow(n2, n1));
else if (str[0] == 'r')
instructions.push(pow(n1, 1.0 / n2));
}
else {
instructions.push(std::stod(trimTrailingZeros(str)));
}
postfix.pop();
}
}
std::string Calculator::getAnswer() {
return trimTrailingZeros(std::to_string(instructions.top()));
}