Here's 4.9 from me... The only thing I'm confused about is whether my reciprocal should show in the NSLog output as a fraction, because I could only figure out how to have it output as a decimal (while retaining it's usefulness in a calculator app).
NOTE: I am using 4.2 with ARC.
Thoughts and comments are appreciated.
//
//
#import <Foundation/Foundation.h>
// ----- Implement a Calculator Class -----
@interface Calculator : NSObject
{
@private
double accumulator;
}
// ----- Accumulator Methods -----
-(void) setAccumulator: (double) value;
-(void) clear;
-(double) accumulator;
-(double) changeSign; // Change sign of accumulator
-(double) reciprocal; // Creates reciprocal of accumulator
-(double) xSquared; // Squares accumulator
// ----- Arithmetic Methods -----
-(double) add: (double) value;
-(double) subtract: (double) value;
-(double) multiply: (double) value;
-(double) divide: (double) value;
@end
@implementation Calculator
-(void) setAccumulator:(double)value
{
accumulator = value;
}
-(void) clear
{
accumulator = 0;
}
-(double) accumulator
{
return accumulator;
}
-(double) add:(double)value
{
accumulator += value;
return accumulator;
}
-(double) subtract:(double)value
{
accumulator -= value;
return accumulator;
}
-(double) multiply:(double)value
{
accumulator *= value;
return accumulator;
}
-(double) divide: (double)value
{
accumulator /= value;
return accumulator;
}
-(double) changeSign
{
return accumulator *= -1;
}
-(double) reciprocal
{
return accumulator = 1/accumulator;
}
-(double) xSquared
{
return accumulator *= accumulator;
}
@end
int main (int argc, const char * argv[])
{
@autoreleasepool {
Calculator *deskCalc = [[Calculator alloc] init];
[deskCalc setAccumulator: 3.0];
NSLog (@"We start with the number %g", [deskCalc accumulator]);
[deskCalc changeSign];
NSLog (@"If we change the sign, it becomes %g", [deskCalc accumulator]);
[deskCalc changeSign];
NSLog (@"Now we'll change it back to %g", [deskCalc accumulator]);
[deskCalc xSquared];
NSLog (@"If we square the number, we get %g", [deskCalc accumulator]);
[deskCalc reciprocal];
NSLog (@"And the reciprocal of our new number is %g, in decimal form", [deskCalc accumulator]);
}
return 0;
}