Exemple #1
0
 Fraction abs() {
     Fraction z = new Fraction();
     if (numerator.compareTo(BigInteger.ZERO) < 0) {
         z.numerator = numerator.negate();
     } else {
         z.numerator = numerator;
     }
     if (denominator.compareTo(BigInteger.ZERO) < 0) {
         z.denominator = denominator.negate();
     } else {
         z.denominator = denominator;
     }
     return z;
 }
Exemple #2
0
 Fraction divide(Fraction y) {
     Fraction z = new Fraction();
     z.numerator = numerator.multiply(y.denominator);
     z.denominator = denominator.multiply(y.numerator);
     z.simplify();
     return z;
 }
Exemple #3
0
 Fraction subtract(Fraction y) {
     Fraction z = new Fraction();
     gcd = denominator.gcd(y.denominator);
     z.denominator = denominator.multiply(y.denominator).divide(gcd);
     z.numerator = numerator.multiply(z.denominator.divide(denominator))
        .subtract(y.numerator.multiply(z.denominator.divide(y.denominator)));
     z.simplify();
     return z;
 }
  public static void main(String[] args) {
    Fraction f1 = new Fraction();
    Fraction f2 = new Fraction();

    for (int i = 1; i <= 4; i++) {
      f1.numerator = 1;
      f1.denominator = 2;
      f2.numerator = 3;
      f2.denominator = 4;

      switch (i) {
        case 1:
          System.out.println("f1=" + f1.numerator + "/" + f1.denominator);
          System.out.println("f2=" + f2.numerator + "/" + f2.denominator);

          f1.add(f2);
          System.out.println("f1+f2=" + f1.numerator + "/" + f1.denominator);
          break;

        case 2:
          f1.add(3);
          System.out.println("f1+3=" + f1.numerator + "/" + f1.denominator);
          break;

        case 3:
          f2.sub(f1);
          System.out.println("f2-f1=" + f2.numerator + "/" + f2.denominator);
          break;

        case 4:
          f2.sub(1);
          System.out.println("f2-1=" + f2.numerator + "/" + f2.denominator);
          break;
      }
    }
  }
Exemple #5
0
 Fraction negate() {
     Fraction z = this;
     z.numerator = z.numerator.negate();
     return z;
 }