-
Notifications
You must be signed in to change notification settings - Fork 0
/
PostfixCalculator.cpp
78 lines (58 loc) · 1.8 KB
/
PostfixCalculator.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
#include "PostficCalculator.h"
#include <iostream>
void Exit(const char* error) {
std::cout << error;
exit(-1);
}
PostfixCalculator::PostfixCalculator() {
_solver = new OperationSolver();
_calculationStack = new Stack<FormulaItem*>();
}
void PostfixCalculator::ValidateResult(FormulaItem* result) {
if (!_calculationStack->IsEmpty()) {
Exit("There are still formulas on the stack, equation is incorrect");
}
if (result->FormulaType != FormulaType::Number) {
Exit("Result is not a number, equation is incorrect");
}
if (result->Value == INFINITY) {
Exit("There were issues with the equations, result was infinity.");
}
}
double PostfixCalculator::Calculate(Stack<FormulaItem*>* postfixStack) {
while (!postfixStack->IsEmpty()) {
FormulaItem* item = postfixStack->Pop();
if (item->FormulaType == FormulaType::Number) {
_calculationStack->Push(item);
}
else if (item->IsProcessable()) {
ProcessOperation(item);
}
}
FormulaItem* result = _calculationStack->Pop();
ValidateResult(result);
return result->Value;
}
void PostfixCalculator::ProcessOperation(FormulaItem* operation) {
double result = 0;
if (operation->NumberOfParameters() == 1) {
double value = GetInput();
result = _solver->SolveSingleParameterFormula(operation, value);
}
if (operation->NumberOfParameters() == 2) {
double secondValue = GetInput();
double firstValue = GetInput();
result = _solver->SolveDoubleParameterFormula(operation, firstValue, secondValue);
}
_calculationStack->Push(new FormulaItem(result));
}
double PostfixCalculator::GetInput() {
if (_calculationStack->IsEmpty()) {
Exit("Formula is incorrect");
}
FormulaItem* input = _calculationStack->Pop();
if (input->FormulaType != FormulaType::Number) {
Exit("Left side of an equation is not a number");
}
return input->Value;
}