"Reduce" Method and Adding Rational Numbers

• November 10th, 2012, 10:12 PM
LoganC
"Reduce" Method and Adding Rational Numbers
This is the part of the homework where I am stuck:
Write a modifier named reduce that reduces a rational number to its lowest terms by finding
the GCD of the numerator and denominator and then dividing top and bottom by the GCD.
• Write a method called add that takes two Rational numbers as arguments and returns a new
Rational object. The return object, not surprisingly, should contain the sum of the two
rational numbers and it should be reduced (using your reduce method, of course).

Here is where I am stuck: This is my current code.
I cannot quite figure out how to set up my reduce method. And I am also having some issues with adding two rational numbers, can anyone add some insight on this?

Code :

```public class MainClass { //Declarationg int num, den;     public MainClass () { //Initalizing Variables this.num = 0; this.den = 0; } public void negate (Rational r) { this.num = -this.num; } public void invert (Rational r) { Math.pow (this.num / this.den, -1); }     public void printRational (Rational r){ System.out.println(this.num + " / " + this.den); } public double toDouble () { return (double) num/den; } public static int gcd (int n, int d) { n = 2; d = 3; if (n < 0) { n = -n; } if (d < 0) { d = -d; } return n * (d / gcd (n, d)); } public double reduce (Rational r) {   } public double add (Rational r1, Rational r2) {   return Rational (add (num + den)); }       public void main(String[] args) { MainClass r1 = new MainClass (); r1.num = 4; r1.den = 12; System.out.println(r1.num + "/" + r1.den); System.out.println("Reduced Amount"); System.out.println(reduce (num + den));   } }```
• November 15th, 2012, 02:04 PM
retsameht
Re: "Reduce" Method and Adding Rational Numbers
you haven't implemented the reduce method yet, once you have implemented the reduce method then you can use it in your add function like this:
r1=reduce(r1);
r2=reduce(r2);
return Rational(r1+r2);