首页 > 代码库 > [Stanford] RPN Calculator (overall design)

[Stanford] RPN Calculator (overall design)

RPN(Reverse Polish Notation),逆波兰表达式。

RPN Calculator is a calculator that uses the Reverse Polish Notation method of user interaction, which is typically popular with people who deal with financial, engineering or other technical problems.

1)The function of the calculator:

    不使用括号,输入数字压入栈,输入加减乘除运算符立即计算栈顶元素的运算结果并将结果压入栈,准备下一步继续运算。

    比如输入5,输入4,输入+,则栈里结果是9(当然可以有更复杂的输入)

2)Overall design

     1) Model design(CalculatorBrain)

            model文件设计如下:用私有栈(NSMutableArray)存储操作数和中间结果,用pushOperand方法,将操作数压入栈,用performOperation方法计算并返回double结果。

           public部分:

@interface CalculatorBrain : NSObject    -(void)pushOperand:(double)operand;   -(double)performOperation:(NSString *)operation;@end

           private部分:

@interface CalculatorBrain() //private的 @property(nonatomic,strong)NSMutableArray *operandStack; //一定要strong,因为只有我们在使用这个指针,strong会告诉编译器怎么管理内存,当property创建时值为0或者nil,发消息给nil什么也不发生 @end

        2)Controller design(CalculatorViewController)

       controller文件设计如下:把view中的label设为outlet,将此outlet作为controller的属性用controller来控制在view上的显示;digitPressed方法用来控制digit键被按下后label的显示;OperationPressed方法控制按下“+”、“-”、“*”、“/”键的运算过程;enterPressed方法将操作数入栈道model的栈里。

       public部分:

@interface CalculatorViewController : UIViewController@property (weak, nonatomic) IBOutlet UILabel *display;          //display------label的,view到controller的outlet@end                              

      private部分:

@interface CalculatorViewController()@property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber; //初始值是0,属于private@property (nonatomic ,strong)CalculatorBrain *brain;@end

      private部分实现的方法,大都是view和controller实现的target action方法:

@implementation CalculatorViewController- (IBAction)digitPressed:(UIButton *)sender;- (IBAction)OperationPressed:(UIButton *)sender;- (IBAction)enterPressed;@end                           

    3)View

     

输入“56 enter 3 +”,就会出现结果“59”

[Stanford] RPN Calculator (overall design)