0

Right now, when running my Rational program I get a 1 when creating a new rational with the numerator being 2 and denominator being 0, and my teacher wants me to replace the denominator with a 1 instead of a 0 but I am unable to and get a stack overflow error whenever trying to add an if in the reduce method that is used to reduce the fractions to their simplest form. I have also tried adding an if statement to the constructor where the rational object containing the numerator and denominator are, but still to no avail. I also have a similar problem when a rational is created with a 0 numerator and 2 in the denominator. It is supposed to return 0/1, but 0 is returned. I believe these two are related, does anyone know what's going on here?

 public Rational(int numerator, int denominator) {
    int gcd = reduce(numerator, denominator);
    num = numerator / gcd;
    denom = denominator / gcd;
    if(denom == 0)
    {
     denom = 1;
    }
    
}

private static int reduce(int numerator, int denominator) {
    if(denominator == 0) numerator = 1;
    return reduce(denominator, numerator % denominator);
}
  • You're getting a stack overflow error because you are calling `reduce` recursively without a stop condition. You say that you want to set the denominator to 1 if the user gives 0. But in your `reduce` method, you set the *numerator* to 1 when the denominator is 0. Is that a mistake? – Matt Jan 04 '21 at 06:10

1 Answers1

0

I don't fully understand the quest and cannot speak to the rational portion of your problem but the stack overflow error is caused by your function reduce. The issue is that there is no endpoint for this function and because it is recursive, function calls will build up on the stack until there is no more space available thus resulting in a stack overflow. The following change will fix the stack overflow error.

private static int reduce(int numerator, int denominator) {
    if(denominator == 0) { //assuming this is the end point
        numerator = 1;  
        return numerator; //this ends the recursive call
    }
    return reduce(denominator, numerator % denominator);
}

If you're looking for a method that finds the greatest common denominator then the following change to your function should work.

private static int reduce(int numerator, int denominator) {
    if(denominator == 0) { 
        return numerator; 
    }
    return reduce(denominator, numerator % denominator);
}
Qifeng Li
  • 33
  • 5