[学习笔记—Objective-C]《Objective-C 程序设计 第6版》第四章 数据类型和表达式 课后练习题 4-10

4-10 题目:
为代码清单 4-6中的Calculator添加一项存储功能。实现以下方法声明并实现它们:

-(double) memoryClear;                  
-(double) memoryStore;                  
-(double) memoryRecall;                
-(double) memoryAdd: (double) value;    
-(double) memorysubtract:(double) value; 

4-10 代码:


#import 


@interface Calculator : NSObject

//累加方法
-(void) setAccumulator: (double) value;
-(void) clear;
-(double) accumulator;


//算术方法

-(void) add: (double) value;
-(void) subtract: (double) value;
-(void) multiply: (double) value;
-(void) divide: (double) value;

//内存功能

-(double) memoryClear;                   //清理内存
-(double) memoryStore;                   //设置内存为累加器
-(double) memoryRecall;                  //设置累加器到内存
-(double) memoryAdd: (double) value;     //添加值到内存
-(double) memorysubtract:(double) value; //与内存的值相减

@end


@implementation Calculator

{
    double accumulator;
    double memory;
}

-(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;
}


//内存功能

-(double) memoryClear
{
    memory = 0;
    return accumulator;
}

-(double) memoryStore
{
    memory = accumulator;
    return accumulator;

}

-(double) memoryRecall
{
    accumulator = memory;
    return accumulator;
}

-(double) memoryAdd: (double) value
{
    memory += value;
    return accumulator;
}

-(double) memorysubtract:(double) value
{
    memory -= value;
    return accumulator;
}


@end


int main(int argc, const char * argv[])
{
    @autoreleasepool {

        Calculator *deskCalc = [[Calculator alloc] init];

        [deskCalc setAccumulator:100.0];
        [deskCalc add:200.];
        [deskCalc divide:15.0];
        [deskCalc subtract:10.0];
        [deskCalc multiply:5];

        NSLog(@"The result is %g", [deskCalc accumulator]);

        [deskCalc memoryStore]; //累加器值添加到内存      
        [deskCalc memoryAdd:5]; //内存值+5       
        [deskCalc memoryRecall];//内存值添加到累加器        
        NSLog(@"The result is %g", [deskCalc accumulator]);

        [deskCalc memorysubtract:10];//内存值-10        
        [deskCalc memoryRecall];     //内存值添加到累加器    
        NSLog(@"The result is %g", [deskCalc accumulator]);

        [deskCalc memoryClear];  //内存值清零
        [deskCalc memoryRecall]; //内存值添加到累加器

        NSLog(@"The result is %g", [deskCalc accumulator]);
  }
    return 0;
}

代码运行结果:

The result is 50
The result is 55
The result is 45
The result is 0

你可能感兴趣的:(iOS,开发)