Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Problem with subtracting a negative fraction

1. ## Problem with subtracting a negative fraction

For some reason, I'm getting the correct result, but my negative sign is having issues. For example, if I do 1/4 - (-2/4), I get (-3/4).

Here is my minus method for subtracting fractions.

```   /**
Subtracts a fraction from another fraction.
@param toUse, the fraction to subtract.
@return minusFraction, the result after subtraction.
*/
public Fraction minus(Fraction toUse)
{
int newNum = ((toUse.numerator * denominator)
- (numerator * toUse.denominator));
int newDen = denominator * toUse.denominator;
Fraction minusFraction = new Fraction(newNum, newDen);

return minusFraction;
}```
Here is my reduce() method, just in case...

```  /**
Reduces the fraction, if possible, to it's simplest form.
Converts negative fractions to the form -x/y, or if -x/-y --> x/y
*/
private void reduce()
{
int lowest = Math.abs(numerator);
int highest = Math.abs(denominator);

if (lowest > highest)
{
int temp = highest;
highest = lowest;
lowest = temp;
}

while (lowest != 0)
{
int temp = lowest;
lowest = highest % lowest;
highest = temp;
}

numerator /= highest;
denominator /= highest;

if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
}```
I only switched an operator from my previous addition method, given here as well. I think only switching the + to a - may have caused my issue.

```   /**
@param toUse, the fraction to be added.
@return plusFraction, the sum of the two fractions.
*/
public Fraction plus(Fraction toUse)
{
int newNum = ((toUse.numerator * denominator)
+ (numerator * toUse.denominator));
int newDen = denominator * toUse.denominator;
Fraction plusFraction = new Fraction(newNum, newDen);

return plusFraction;
}```  Reply With Quote

3. ## Re: Problem with subtracting a negative fraction

I think you may want to change

int newNum = ((toUse.numerator * denominator)
- (numerator * toUse.denominator));

With

int newNum = ((numerator * toUse.denominator)
- (toUse.numerator * denominator));

- Jim  Reply With Quote