Home   Cover Cover Cover Cover
 

Unterklassen

A06.cs
using System;

class Fraction {
  protected int z, n;
  
  public Fraction(int z, int n) {
    this.z = z; this.n = n;
  }
  
  public static Fraction operator + (Fraction a, Fraction b) {
    return new Fraction(a.z * b.n + a.n * b.z, a.n * b.n);
  }
    
  public static Fraction operator * (Fraction a, Fraction b) {
    return new Fraction(a.z * b.z, a.n * b.n);
  }
  
  public override string ToString() {
    return z + "/" + n;
  }
}

class BetterFraction: Fraction {
  
  public BetterFraction(int z, int n): base(z, n) {}
  
  private int GCD(int a, int b) { // greatest common divisor of a and b
    int rest = a % b;
    while (rest != 0) {
      a = b; b = rest; rest = a % b;
    }
    return b;
  }
  
  public void Reduce() {
    int d = GCD(z, n);
    z = z / d; n = n / d;
  }
  
  public static BetterFraction operator + (BetterFraction a, BetterFraction b) {
    BetterFraction f = new BetterFraction(a.z * b.n + a.n * b.z, a.n * b.n);
    f.Reduce();
    return f;
  }
    
  public static BetterFraction operator * (BetterFraction a, BetterFraction b) {
    BetterFraction f = new BetterFraction(a.z * b.z, a.n * b.n);
    f.Reduce();
    return f;
  }
  
}

class Test {
  
  static void Main(string[] arg) {
    BetterFraction a = new BetterFraction(1, 2);
    BetterFraction b = new BetterFraction(3, 4);
    Console.WriteLine((a + b) + " " + a * b);
  }
  
}