-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.cpp
More file actions
100 lines (81 loc) · 2.74 KB
/
calculator.cpp
File metadata and controls
100 lines (81 loc) · 2.74 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
#include <iostream>
#include <cstring>
#include <bits/stdc++.h>
#include <math.h>
#include <string>
#include <algorithm>
#include "infixToPostfix.h"
using namespace std;
struct Calculator {
double calculate(string post_equation) {
stack <double> mystack;
// loop to iterate through the equation
for (int i = 0; i < post_equation.length(); i++)
{
//if the character is blank space then continue
if(post_equation[i] == ' ') {
continue;
}
// if the character is an operand we push it in the stack
else if (isdigit(post_equation[i]))
{
string num;
//extract full number
while(isdigit(post_equation[i]) || post_equation[i] == '.')
{
num += post_equation[i];
i++;
}
i--;
//push the element in the stack
mystack.push(stod(num));
}
// if the character is an operator
else
{
// pop the top two elements from the stack and save them in two integers
double x = mystack.top();
mystack.pop();
double y = mystack.top();
mystack.pop();
//switch statement for operators
switch (post_equation[i])
{
case '+': // addition
mystack.push(y + x);
break;
case '-': // subtraction
mystack.push(y - x);
break;
case '*': // multiplication
mystack.push(y * x);
break;
case '/': // division
mystack.push(y / x);
break;
case '^': // exponent
mystack.push(pow(y,x));
break;
}
}
}
//returning the calculated result
return mystack.top();
}
};
int main() {
string equation;
string postfixEquation;
Calculator c;
while(equation != "quit") {
//get equation from user input
printf("%s \n", "Enter your equation (hit: enter quit to exit): ");
getline(cin, equation);
//Ignore the whiter space
equation.erase(remove(equation.begin(), equation.end(), ' '), equation.end());
//create postfix equation
postfixEquation = infixToPostfix(equation);
printf("The result of the equation is: %g\n\n",c.calculate(postfixEquation));
}
return 0;
}