-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculatorBrain.m
109 lines (91 loc) · 2.13 KB
/
CalculatorBrain.m
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
105
106
107
108
109
//
// CalculatorBrain.m
// Calculator
//
// Created by David Pullar on 1/20/2014.
// Copyright (c) 2014 David Pullar. All rights reserved.
//
#import "CalculatorBrain.h"
@implementation CalculatorBrain
- (id)init {
self = [super init];
if (self) {
lhs = 0;
rhs = 0;
op = @"";
}
return self;
}
- (NSString *)operator {
return op;
}
- (void)setOperator:(NSString *)currOp {
op = currOp;
}
- (double)operand {
return rhs;
}
- (void)setOperand:(double)operand {
lhs = rhs;
rhs = operand;
}
- (void)memoryStorage:(double)operand {
memory = operand;
}
- (void)memoryClear {
memory = 0;
}
- (double)memoryRecall {
return memory;
}
- (void)memoryAdd:(double)operand {
memory += operand;
}
- (void)memorySubtract:(double)operand {
memory -= operand;
}
- (int)factorial:(int)n {
if (n == 1)
return n;
else
return n * [self factorial:n - 1];
}
- (double)performOperation:(NSString *)operation {
if ([operation isEqual:@"+"]) {
lhs += rhs;
} else if ([operation isEqual:@"-"]) {
lhs -= rhs;
} else if ([operation isEqual:@"x"]) {
lhs *= rhs;
} else if ([operation isEqual:@"÷"]) {
if (rhs)
lhs /= rhs;
} else if ([operation isEqual:@"sin"]) {
lhs = sin(rhs);
} else if ([operation isEqual:@"cos"]) {
lhs = cos(rhs);
} else if ([operation isEqual:@"tan"]) {
lhs = tan(rhs);
} else if ([operation isEqual:@"n!"]) {
lhs = [self factorial:rhs];
} else if ([operation isEqual:@"√x"]) {
lhs = sqrt(rhs);
} else if ([operation isEqual:@"x²"]) {
lhs = pow(rhs, 2);
} else if ([operation isEqual:@"log₂"]) {
lhs = log2(rhs);
} else if ([operation isEqual:@"ln"]) {
lhs = log(rhs);
} else if ([operation isEqual:@"xʸ"]) {
lhs = pow(lhs, rhs);
} else if ([operation isEqual:@"%"]) {
lhs = fmod(lhs, rhs);
} else if ([operation isEqual:@"1/x"]) {
if (rhs)
lhs = 1 / rhs;
} else if ([operation isEqual:@"+/-"]) {
lhs = -1 * rhs;
}
return lhs;
}
@end