Created
July 17, 2012 18:26
-
-
Save voxxit/3131114 to your computer and use it in GitHub Desktop.
My first Objective-C program :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Fraction.h | |
// | |
#import <Foundation/Foundation.h> | |
@interface Fraction : NSObject | |
@property int numerator, denominator; | |
-(void) print; | |
-(void) setTo: (int) n over: (int) d; | |
-(void) add: (Fraction *) f; | |
-(double) convertToNum; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Fraction.m | |
// | |
#import "Fraction.h" | |
@implementation Fraction | |
@synthesize numerator, denominator; | |
-(void) print { | |
NSLog(@"%i/%i", numerator, denominator); | |
} | |
-(double) convertToNum { | |
if (denominator != 0) { | |
return (double) numerator / denominator; | |
} else { | |
return NAN; | |
} | |
} | |
-(void) setTo:(int)n over:(int)d { | |
numerator = n; | |
denominator = d; | |
} | |
-(void) add: (Fraction *) f { | |
// To add two fractions: | |
// a/b + c/d = ((a*d) + (b*c)) / (b*d) | |
numerator = numerator * f.denominator + denominator * f.numerator; | |
denominator = denominator * f.denominator; | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// New program separating the files of the Fraction program. | |
#import <Foundation/Foundation.h> | |
#import "Fraction.h" | |
int main(int argc, const char * argv[]) { | |
@autoreleasepool { | |
Fraction *aFraction = [[Fraction alloc] init]; | |
Fraction *bFraction = [[Fraction alloc] init]; | |
// Set two fractions to 1/4 and 1/2, and add them together | |
[aFraction setTo: 1 over: 4]; | |
[bFraction setTo: 1 over: 2]; | |
// Display the results | |
[aFraction print]; | |
NSLog(@"+"); | |
[bFraction print]; | |
NSLog(@"="); | |
[aFraction add: bFraction]; | |
[aFraction print]; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment