第18章练习的解决方案 solution


#1

大家好,我是来自中国的一位 Objective-c 初学者。请多指教
I’m from china ,and … I’m trying hard in learning English:smile:
以下是本书 18章练习的答案。
有什么不对请大家多多指出。
I can use Google translation communicate with you
------------------BNRStockHolding.h---------------------

#import <Foundation/Foundation.h>

@interface BNRStockHolding : NSObject
{
    float _purchaseSharePrice;
    float _currentSharePrice;
    int _numberOfShares;
}

-(float)costInDollars;
-(float)valueInDollars;
-(void)setPucrhaseSharePrice:(float)p;
-(void)setCurrentSharePrice:(float)c;
-(void)setNumberOfShares:(int)n;

@end

-------------BNRStockHolding.m-----------------------

#import "BNRStockHolding.h"

@implementation BNRStockHolding

-(float)costInDollars
{
    return _purchaseSharePrice * _numberOfShares;
}

-(float)valueInDollars
{
    return _currentSharePrice * _numberOfShares;
}

-(void)setPucrhaseSharePrice:(float)p
{
    _purchaseSharePrice = p;
}

-(void)setCurrentSharePrice:(float)c
{
    _currentSharePrice = c;
}
-(void)setNumberOfShares:(int)n;
{
    _numberOfShares = n;
}

-----------------that is main.c----------------------------

#import <Foundation/Foundation.h>
#import "BNRStockHolding.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        BNRStockHolding *one = [[BNRStockHolding alloc] init];
        BNRStockHolding *two = [[BNRStockHolding alloc] init];
        BNRStockHolding *three = [[BNRStockHolding alloc] init];
        
        [one setPucrhaseSharePrice:2.30];
        [one setCurrentSharePrice:4.50];
        [one setNumberOfShares:40];
        
        [two setPucrhaseSharePrice:12.19];
        [two setCurrentSharePrice:10.56];
        [two setNumberOfShares:90];
        
        [three setPucrhaseSharePrice:45.10];
        [three setCurrentSharePrice:49.51];
        [three setNumberOfShares:210];
        
        NSMutableArray *array = [NSMutableArray array];
        [array addObject:one];
        [array addObject:two];
        [array addObject:three];
        
        for(BNRStockHolding *d in array){
            NSLog(@"%.2f", [d costInDollars]);
            NSLog(@"%.2f", [d valueInDollars]);
            NSLog(@"\n");
            
        }
    }
    return 0;
}

#2

cookies_J 你好!

虽然我是美国人,我自学中文
我看到了你的问题.

我不知道答案,但是我翻译了您的消息所以美国人可以帮你
加油 :laughing:


Hello everyone, I am from China and am a beginning student of Objective-C. Please give me some advice.

Here are the answers to Exercises from Chapter 18 of the book.

What is wrong with this code? Please don’t hesitate to point out any mistakes! :slight_smile:


Hey guys, I unfortunately don’t know the answer… but, I study chinese, so I went ahead and translated his question so hopefully you can help him! :smiley:


#3

Thank you very much!
谢谢!感激不尽!


#4

I added another three getter methods when I created my class and I donnot know if it is necessary or right.