-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;
while (temp !=0) {
temp = u % v;
u = v;
v = temp;
}
numerator /=u;
denominator /=v;
}
views:
51answers:
2You are dividing by zero. I think the last line should be,
denominator /= u;
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.