Program 7.6 is giving me some trouble. I typed in the code, and added in my own personal comments, as well as stuff from the book, to help me understand it better.
And yet, when I run it, i get an error message in the reduce method. "Thread 1: Program received signal: "EXC_ARITHMETIC". Upon further examination in the debug window, it says that all the variables in the reduce method are zero.
Here's the code (I'll remove my personal comments):
Fraction.h
#import <Foundation/Foundation.h>
// The Fraction class
@interface Fraction : NSObject {
int numerator;
int denominator;
}
@property int numerator, denominator;
-(void) print;
-(void) setTo: (int) n over: (int) d;
-(double) convertToNum;
//-(void) add: (Fraction *) f;
-(Fraction *) add: (Fraction *) f;
-(void) reduce;
@end
Fraction.m
#import "Fraction.h"
@implementation Fraction
@synthesize numerator, denominator;
-(void) print {
NSLog(@"%i/%i", numerator, denominator);
}
-(void) setTo: (int) n over: (int) d {
numerator = n;
denominator = d;
}
-(double) convertToNum {
if( denominator != 0 )
return ((double) numerator) / denominator;
else
return 1.0;
}
-(Fraction *) add: (Fraction *) f {
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;
//declare the new num / denom variables
resultNum = numerator * f.denominator + denominator * f.numerator;
resultDenom = denominator * f.denominator;
//set the new fraction
[result setTo: resultNum over: resultDenom];
[result reduce];
return result;
}
//method to reduce the fraction
-(void) reduce {
int u = numerator; //u turns out to store the gcd
int v = denominator;
int temp;
//loop through this process to find the gcd
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
//divide numerator & denominator by gdc
//here is where the debug window shows the error
numerator /= u;
denominator /= u;
}
@end
main.m
/*
Algorithm to perform the following operation:
n
Σ (1/2)^i
i 1
Sum the values of (1/2)^i, as i increases from 1 --> n
*/
#import "Fraction.h"
int main(int argc, char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Fraction *aFraction = [[Fraction alloc] init];
Fraction *sum = [[Fraction alloc] init], *sum2;
int i, n, pow2;
//set 1st fraction to 0
[sum setTo: 0 over: 1];
NSLog(@"Enter a value for n:");
scanf("%i", &n);
pow2 = 0;
for( i = 1 ; i <= n ; i++ ) {
[aFraction setTo: 1 over: pow2];
sum2 = [sum add: aFraction];
[sum release]; //release previous sum
sum = sum2;
pow2 *= 2;
}
NSLog(@"After %i iterations, the sum is %f", n, [sum convertToNum]);
[aFraction release];
[sum release];
[pool drain];
return 0;
}
Thanks in advance for any answers!