tags:

views:

51

answers:

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

 while (temp !=0) {

  temp = u % v;
  u = v;
  v = temp;
 }

 numerator /=u;
 denominator /=v;
}
+2  A: 

You are dividing by zero. I think the last line should be,

denominator /= u;
Dietrich Epp
That's it! How did you see it so quickly?
lampShade
I should also note that this crashes your program or doesn't depending on the OS and processor. On OS X PPC it doesn't crash, it just gives the wrong answer.
Dietrich Epp
The reason I could see it so quickly is because there is only one possible problem in integer code that could cause a crash: division by zero.
Dietrich Epp
Thank you. Now I have another tip!
lampShade
A: 

Also: you haven't initialized temp.

I think you're lucking out and getting a non-zero value in there. This gets you into the loop, which runs and calculates things properly until temp is zero. Since v gets temp's value at the bottom of the loop, when temp is zero for the loop termination condition, v is too. So when you divide by v, blam.

Initialize temp = 1 before you start the loop to avoid a Heisenbug down the road. Since the variable contains garbage when it's allocated on the stack, the chances are high that it will be nonzero, but not definitely, so every once in a while, you get a wrong answer without warning. That will be a royal pain to find.

Last: choose different names for your variables! FORTRAN is so passé. If you'd called then targetDenominator and targetNumerator, you probably would not have written

numerator /= targetNumerator;
denominator /= targetDenominator;

... or at least it would have been clearer you'd made the error.

Joe McMahon