-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.cpp
More file actions
103 lines (92 loc) · 2.92 KB
/
Calculator.cpp
File metadata and controls
103 lines (92 loc) · 2.92 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
float toRadians(float degrees) {
return degrees * M_PI / 180.0;
}
float power(float base, int exponent) {
float result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
float find(const string& s) {
if (s.substr(0, 2) == "ln") {
int start = s.find('(');
int end = s.find(')');
return log(stof(s.substr(start + 1, end - start - 1)));
} else if (s.substr(0, 3) == "log") {
int startBase = 3;
int startNum = s.find('(');
int endNum = s.find(')');
return log(stof(s.substr(startNum + 1, endNum - startNum - 1))) /
log(stof(s.substr(startBase, startNum - startBase)));
} else if (s.substr(0, 3) == "sin") {
int start = s.find('(');
int end = s.find(')');
float val = stof(s.substr(start + 1, end - start - 1));
return sin(toRadians(val));
} else if (s.substr(0, 3) == "cos") {
int start = s.find('(');
int end = s.find(')');
float val = stof(s.substr(start + 1, end - start - 1));
return cos(toRadians(val));
} else if (s.substr(0, 3) == "tan") {
int start = s.find('(');
int end = s.find(')');
float val = stof(s.substr(start + 1, end - start - 1));
return tan(toRadians(val));
} else if (s.substr(0, 4) == "root") {
int degree = stoi(s.substr(4, s.find('(') - 4));
int start = s.find('(');
int end = s.find(')');
float number = stof(s.substr(start + 1, end - start - 1));
return pow(number, 1.0 / degree);
} else {
return stof(s);
}
}
int main() {
float result = 0.0, number;
char operation;
bool firstInput = true;
string s1, s2;
cout << "Continuous Calculator\n";
cout << "Enter 'q' or 'Q' as operation to quit.\n";
while (true) {
if (firstInput) {
cin >> s1;
result = find(s1);
firstInput = false;
}
cin >> operation;
if (operation == 'q' || operation == 'Q') {
cout << "Calculator stopped. Final result = " << result << endl;
break;
}
cin >> s2;
number = find(s2);
switch (operation) {
case '+': result += number; break;
case '-': result -= number; break;
case '*': result *= number; break;
case '/':
if (number == 0) {
cout << "Error: Division by zero!\n";
continue;
}
result /= number;
break;
case '^':
result = power(result, (int)number);
break;
default:
cout << "Invalid operation!\n";
continue;
}
cout << "Current result: " << result << endl;
cout << result << " ";
}
return 0;
}