Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
April 22, 2018, 09:24:41 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
 
   Home   Help Search Login Register Chat  
Pages: [1]   Go Down
  Print  
Author Topic: Program 10.1  (Read 2370 times)
esc
Global Moderator
Full Member
*****
Posts: 230


« on: February 25, 2009, 02:39:49 AM »

Fraction.h
Code: (Objective-C)
#import <Foundation/Foundation.h>

@interface Fraction : NSObject {
int numerator;
int denominator;
}

@property int numerator, denominator;

-(Fraction *) initWith: (int) n: (int) d;
-(void) print;
-(void) setTo: (int) n over: (int) d;
-(double) convertToNum;
-(void) reduce;
-(Fraction *) add: (Fraction *) f;

@end

Fraction.m
Code: (Objective-C)
#import "Fraction.h"

@implementation Fraction

@synthesize numerator, denominator;

-(Fraction *) initWith: (int) n: (int) d
{
self = [super init];

if (self)
[self setTo: n over: d];

return self;
}

-(void) print
{
NSLog (@"%i/%i", numerator, denominator);
}

-(double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return 1.0;
}

-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}

-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;

while (v != 0) {
temp = u % v;
u = v;
v = temp;
}

numerator /= u;
denominator /= u;
}

-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c) / (b * d)

// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;

resultNum = numerator * f.denominator + denominator * f.numerator;
resultDenom = denominator * f.denominator;

[result setTo: resultNum over: resultDenom];
[result reduce];

return result;
}

@end

Program 10.1
Code: (Objective-C)
#import "Fraction.h"

int main (int argc, char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

Fraction *a, *b;

a = [[Fraction alloc] initWith: 1: 3];
b = [[Fraction alloc] initWith: 3: 7];

[a print];
[b print];

[a release];
[b release];

    [pool drain];
    return 0;
}
Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents ゥ 2009 classroomM.com. All rights reserved.