calculator

//  ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *display;

- (IBAction)digitpressed:(id)sender;

@end

 //  ViewController.m


#import "ViewController.h"
#import "CalculatorBrain.h"

@interface ViewController()
@property (nonatomic)BOOL userIsInTheMiddleOfEnteringANumber;
@property (nonatomic,strong)CalculatorBrain *brain;
@end


@implementation ViewController
@synthesize display=_display;
@synthesize userIsInTheMiddleOfEnteringANumber=_userIsInTheMiddleOfEnteringANumber;
@synthesize brain=_brain;

-(CalculatorBrain *)brain
{
if(!_brain)_brain=[[CalculatorBrain alloc]init];
return _brain;
}
- (IBAction)digitpressed:(UIButton *)sender {
NSString *digit=[sender currentTitle];
if(self.userIsInTheMiddleOfEnteringANumber){
self.display.text=[self.display.text stringByAppendingString:digit];
}
else{
self.display.text=digit;
self.userIsInTheMiddleOfEnteringANumber=YES;
}
}
- (IBAction)operationPressed:(UIButton *)sender {
if(self.userIsInTheMiddleOfEnteringANumber)[self enterPressed];
double result = [self.brain performOperation:sender.currentTitle];
NSString *resultString = [NSString stringWithFormat:@"%g",result];
self.display.text = resultString;
}
- (IBAction)enterPressed {
[self.brain pushOperand:[self.display.text doubleValue]];
self.userIsInTheMiddleOfEnteringANumber=NO;
}
@end

 

// CalculatorBrain.h

#import <Foundation/Foundation.h>

@interface CalculatorBrain : NSObject

-(void)pushOperand:(double)operand;
-(double)performOperation:(NSString *)operation;

@end

// CalculatorBrain.m

#import "CalculatorBrain.h"

@interface CalculatorBrain()

@property(nonatomic ,strong)NSMutableArray *operandStack;


@end


@implementation CalculatorBrain
@synthesize operandStack=_operandStack;
-(NSMutableArray *)operandStack
{
if(_operandStack==nil)
_operandStack=[[NSMutableArray alloc]init];
return _operandStack;
}

-(double)popOperand
{
NSNumber *operandObject=[self.operandStack lastObject];
if(operandObject)[self.operandStack removeLastObject];
return [operandObject doubleValue];
}
-(void)pushOperand:(double)operand
{

[self.operandStack addObject:[NSNumber numberWithDouble:operand]];
}
-(double)performOperation:(NSString *)operation
{
double result=0;
//calculate result
if([operation isEqualToString:@"+"])
{
result=[self popOperand]+[self popOperand];
}
else if([@"*" isEqualToString:operation])
{
result = [self popOperand]*[self popOperand];

}
[self pushOperand:result];

return result;
}

@end

posted @ 2015-03-22 23:05  锄,禾日当午  阅读(180)  评论(0编辑  收藏  举报