I'm creating a program that adds and subtracts fractions together. That being said however, my program does not seem to be responding correctly. Every time I run the client code, it outputs
4/4, when I want it to add 1/2 and 1/2 (instead of 1), and 6/36, when I subtract 2/6 and 1/6 (instead of 1/6). My constructor code and client code is as follows:
Hopefully this code segment is sufficient enough in exchange for your help. Thank you for your time.
4/4, when I want it to add 1/2 and 1/2 (instead of 1), and 6/36, when I subtract 2/6 and 1/6 (instead of 1/6). My constructor code and client code is as follows:
Code:
// Constructor //
public class RationalNumber
{
int num;
int den;
private int gcd(int x, int y)
{
while(y != 0)
{
int temp = x % y;
x = y;
y = temp;
}
return x;
}
public void reduce()
{
int d;
while (true)
{
d = this.gcd(this.num,this.den);
if (d == 1)
{
return;
}
this.num /= d;
this.den /= d;
}
}
public RationalNumber add(RationalNumber r1)
{
int commonDen = den * r1.getDenominator();
int num1 = num * r1.getDenominator();
int num2 = r1.getNumerator() * den;
int sum = num1 + num2;
return new RationalNumber (sum, commonDen);
}
public RationalNumber sub(RationalNumber r1)
{
int commonDen = den * r1.getDenominator();
int num1 = num * r1.getDenominator();
int num2 = r1.getNumerator() * den;
int dif = num1 - num2;
return new RationalNumber (dif, commonDen);
}
}
Code:
// Client Code //
public class RationalTest
{
public static void main (String[] args)
{
RationalNumber r1 = new RationalNumber(2,6);
RationalNumber r2 = new RationalNumber(1,6);
RationalNumber r3 = new RationalNumber(1,2);
RationalNumber r4 = new RationalNumber(1,2);
System.out.println(r1.add(r2));
System.out.println(r3.sub(r4));
}
}
Comment