I worked ahead on this over the weekend. Here's my solution:
Calculator.h#import <Foundation/Foundation.h>
@interface Calculator : NSObject {
double accumulator;
}
// accumulator methods
-(void) setAccumulator: (double) value;
-(void) clear;
-(double) accumulator;
// arithmetic methods
-(void) add: (double) value;
-(void) subtract: (double) value;
-(void) multiply: (double) value;
-(void) divide: (double) value;
@end
Calculator.m#import "Calculator.h"
@implementation Calculator
-(void) setAccumulator: (double) value
{
accumulator = value;
}
-(void) clear
{
accumulator = 0;
}
-(double) accumulator
{
return accumulator;
}
-(void) add: (double) value
{
accumulator += value;
}
-(void) subtract: (double) value
{
accumulator -= value;
}
-(void) multiply: (double) value
{
accumulator *= value;
}
-(void) divide: (double) value
{
accumulator /= value;
}
@end
Ex6-4.m#import "Calculator.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
double value;
char operator;
Calculator *deskCalc = [[Calculator alloc] init];
do {
NSLog (@"Type in your expression in the format: number operator");
scanf ("%lf %c", &value, &operator);
switch (operator) {
case '+':
[deskCalc add: value];
NSLog (@"= %f", [deskCalc accumulator]);
break;
case '-':
[deskCalc subtract: value];
NSLog (@"= %f", [deskCalc accumulator]);
break;
case '*':
[deskCalc multiply: value];
NSLog (@"= %f", [deskCalc accumulator]);
break;
case '/':
[deskCalc divide: value];
NSLog (@"= %f", [deskCalc accumulator]);
break;
case 'S':
[deskCalc setAccumulator: value];
NSLog (@"= %f", [deskCalc accumulator]);
break;
case 'E':
NSLog (@"End of program.");
NSLog (@"= %f", [deskCalc accumulator]);
break;
default:
NSLog (@"Unknown operator.");
break;
}
}
while (operator != 'E');
[deskCalc release];
[pool drain];
return 0;
}
Results2010-03-09 20:13:22.075 Ex6-4[1062:a0f] Type in your expression in the format: number operator
10 S
2010-03-09 20:13:59.321 Ex6-4[1062:a0f] = 10.000000
2010-03-09 20:13:59.322 Ex6-4[1062:a0f] Type in your expression in the format: number operator
2 /
2010-03-09 20:14:06.929 Ex6-4[1062:a0f] = 5.000000
2010-03-09 20:14:06.929 Ex6-4[1062:a0f] Type in your expression in the format: number operator
55 -
2010-03-09 20:14:11.513 Ex6-4[1062:a0f] = -50.000000
2010-03-09 20:14:11.513 Ex6-4[1062:a0f] Type in your expression in the format: number operator
100.25 S
2010-03-09 20:14:18.832 Ex6-4[1062:a0f] = 100.250000
2010-03-09 20:14:18.833 Ex6-4[1062:a0f] Type in your expression in the format: number operator
4 *
2010-03-09 20:14:22.944 Ex6-4[1062:a0f] = 401.000000
2010-03-09 20:14:22.945 Ex6-4[1062:a0f] Type in your expression in the format: number operator
0 E
2010-03-09 20:14:27.936 Ex6-4[1062:a0f] End of program.
2010-03-09 20:14:27.937 Ex6-4[1062:a0f] = 401.000000