Pergunta

In this class there is a Rational constructor that takes two numbers as parameters and turns them into a fraction. It uses the private method gcd to reduce the fraction into the lowest possible terms.

The part I don't understand why the Rational constructor is taking the Math.abs(y) when calculating for dem and the purpose behind the if condition. So when reading the if condition is the method saying if the denominator is less than 0 like for example -4, will den = -4 or will num change to positive 4? If for example you have (-4, -8) for the Rational parameters will the Rational's constructor value be 1/2 or -1/ -2?

public class Rational { 

 public Rational (int x, int y){
    int g = gcd(Math.abs(x), Math.abs(y));
    num = x / g;
    dem = Math.abs(y) / g;
    if ( y < 0 ) num = -num;   
   }


 private int gcd(int x, int y){
    int r = x % y;
    while (r != 0){
    x = y;
    y = r; 
    r = x % y;
     }
   return y;
   }

 private int num;
 private int dem;
 }
Foi útil?

Solução

The writer of this class want the sign to be carried by the numerator. The denominator is always positive. So indeed if the input is 6/-8 the result will be -3/4. Your other example is also correct: -6/-8 construct 3/4.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top