My concern is this: Exercise 8 specifically suggests to have the arithmetic methods return the value of the accumulator...and test this functionality. Obviously it's easy to display the value of the accumulator...but how can we show that the return statements we added to the add, subtract, etc. methods are doing anything? I haven't figured out a way to do this...
You're right. Here's what I did to show the return statements we added. I borrowed from judflo.
The key line here is:
NSLog(@"%f / %f = %f", [deskCalc accumulator], c, [deskCalc divide:c]);
which accesses and returns the return value saved in the divide method.
[#import <Foundation/Foundation.h>
@interface Calculator: NSObject
//acumulator methods
-(void) setAccumulator: (double) value;
-(void) clear;
-(double) accumulator;
//arithmetic methods
-(double) add: (double) value;
-(double) subtract: (double) value;
-(double) multiply: (double) value;
-(double) divide: (double) value;
@end
@implementation Calculator
{double accumulator, add, subtract, multiply, divide;}
-(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;}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
Calculator *deskCalc=[[Calculator alloc] init];
double z, a, s, m, d;
z=100;
a=200;
d=15;
s=10;
m=5;
[deskCalc setAccumulator:z];
NSLog(@"%f+%f=%f",[deskCalc accumulator],a,[deskCalc add:a]);
NSLog(@"%f-%f=%f",[deskCalc accumulator],d,[deskCalc divide:d]);
NSLog(@"%f-%f=%f",[deskCalc accumulator],s,[deskCalc subtract:s]);
NSLog(@"%f-%f=%f",[deskCalc accumulator],m,[deskCalc multiply:m]);
NSLog (@"The result is %f", [deskCalc accumulator]);
}
return 0;
}