-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.cpp
99 lines (93 loc) · 3.72 KB
/
calc.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
#include "calc.hpp"
namespace Calc {
bool calc::analysis(string mathematical_str, vector < double > & num , vector < char > & opr) {
while (mathematical_str.size()) {
if ((mathematical_str[0] >= '0' && mathematical_str[0] <= '9') || mathematical_str[0] == '.'){
_str.push_back(mathematical_str[0]);
mathematical_str.erase(mathematical_str.begin());
} else if (mathematical_str[0] == '+' || mathematical_str[0] == '-' ||
mathematical_str[0] == '*' || mathematical_str[0] == '/' ||
mathematical_str[0] == '^') {
if (_str.empty())
num.push_back(0);
else {
num.push_back(stof(_str));
_str.clear();
}
opr.push_back(mathematical_str[0]);
mathematical_str.erase(mathematical_str.begin());
} else if (mathematical_str[0] == '=') {
if (_str.empty())
num.push_back(0);
else {
num.push_back(stof(_str));
_str.clear();
}
mathematical_str.erase(mathematical_str.begin());
if (!mathematical_str.empty()) {
while (mathematical_str.size()) {
if (mathematical_str[0] == ' ')
mathematical_str.erase(mathematical_str.begin());
else {
cout << endl << "\terror ... " << endl << endl;
return 0;
}
}
}
return 1;
} else if (mathematical_str[0] == ' ') {
mathematical_str.erase(mathematical_str.begin());
} else {
cout << endl << "\t" << mathematical_str[0] << " Unsupported symbol." << endl << endl;
return 0;
}
}
cout << endl << "\tsymbol \" = \" not found." << endl << endl;
_str.clear();
return 0;
}
bool calc::get_result (vector < double > num , vector < char > opr , double & result) {
ctr = 0;
while (ctr < int(opr.size())) {
if (opr[ctr] == '^') {
num[ctr] = pow(num[ctr],num[ctr + 1]);
num.erase(num.begin() + ctr + 1);
opr.erase(opr.begin() + ctr);
} else
ctr++;
}
ctr = 0;
while (ctr < int(opr.size())) {
if (opr[ctr] == '*') {
num[ctr] *= num[ctr + 1];
num.erase(num.begin() + ctr + 1);
opr.erase(opr.begin() + ctr);
} else if (opr[ctr] == '/') {
if (num[ctr + 1]) {
num[ctr] /= num[ctr + 1];
num.erase(num.begin() + ctr + 1);
opr.erase(opr.begin() + ctr);
} else {
cout << endl << "\tCan't divide by zero." << endl << endl;
return 0;
}
} else
ctr++;
}
ctr = 0;
while (ctr < int(opr.size())) {
if (opr[ctr] == '+') {
num[ctr] += num[ctr + 1];
num.erase(num.begin() + ctr + 1);
opr.erase(opr.begin() + ctr);
} else if (opr[ctr] == '-') {
num[ctr] -= num[ctr + 1];
num.erase(num.begin() + ctr + 1);
opr.erase(opr.begin() + ctr);
} else
ctr++;
}
result = num[0];
return 1;
}
}