Note that there are some explanatory texts on larger screens.

plurals
  1. POMath function not showing correct results
    primarykey
    data
    text
    <p>I need some help getting correct results on fraction results. After adding them together and reducing, they should show a final result of 3/4, but I'm getting a result of 3/1. Can you show me where my functions are wrong?</p> <p>Fraction.h</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; //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; -(void) reduce; @end </code></pre> <p>Fraction.m </p> <pre><code>#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 1.0; } -(void) setTo:(int)n over:(int)d{ numerator = n; denominator = d; } //add a fraction to the receiver -(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 = [f denominator]; [self reduce]; } -(void) reduce{ int u = numerator; int v = denominator; int temp; while (v!=0) { temp = u % v; u = v; v = temp; } numerator /= u; denominator /= u; } @end </code></pre> <p>FractionTest.m</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import "Fraction.h" int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 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]; //Print the results [aFraction print]; NSLog(@"+"); [bFraction print]; NSLog(@"="); [aFraction add:bFraction]; //reduce the result of the addition and print the result [aFraction reduce]; [aFraction print]; [aFraction release]; [bFraction release]; [pool drain]; return 0; } </code></pre> <p>Can you tell what I'm doing wrong? TIA</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload