Fraction.h#import <Foundation/Foundation.h>
@interface Fraction : NSObject
{
int numerator, denominator;
}
@property int numerator, denominator;
-(void) print;
-(double) convertToNum;
-(void) setTo: (int) n over: (int) d;
-(Fraction *) reduce;
@end
Fraction.m#import "Fraction.h"
static int gcd (int u, int v)
{
int temp;
while (v) {
temp = u % v;
u = v;
v = temp;
}
return u;
}
@implementation Fraction
@synthesize numerator, denominator;
-(void) print
{
if(denominator < 0)
{
denominator = -denominator;
numerator = -numerator;
}
if(!denominator || !numerator)
NSLog(@"0");
else if(denominator == 1)
NSLog(@"%i", numerator);
else
{
if(numerator < 0)
{
if (-numerator > denominator)
NSLog(@"%i %i/%i", numerator/denominator, -numerator%denominator, denominator);
else
NSLog(@"%i/%i", numerator, denominator);
}
else if (numerator > denominator)
NSLog(@"%i %i/%i", numerator/denominator, numerator%denominator, denominator);
else
NSLog(@"%i/%i", numerator, denominator);
}
}
-(double) convertToNum
{
if(denominator)
return (double) numerator/denominator;
return 0.0;
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
-(Fraction *) reduce
{
int u = gcd(numerator, denominator);
numerator /= u;
denominator /= u;
return self;
}
@end
main.m#import <Foundation/Foundation.h>
#import "Fraction.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *f1 = [[Fraction alloc] init];
Fraction *f2 = [[Fraction alloc] init];
[f1 setTo: 25 over: 50];
[f2 setTo: 49 over: 21];
[f1 reduce];
[f2 reduce];
[f1 print];
[f2 print];
[f1 release];
[f2 release];
[pool drain];
return 0;
}
The way I see it, the only benefit from making the function static is that
it stays private to the file. Another one is thaht it doesn't create new variables every time it is called
I think that using functions is better than using the whole code.
Mainly because it provides more readable, cleaner code and because you have a "source code", so you don't have to
change every sample of the code, just the source. Afcourse in this case, it doesn't matter.