/** * 有理數sample; 有理數謂之:2/3,4/6就是咱們說的分數 * @param a 分子 * @param b 分母 */ class Rational(a:Int, b:Int) { require( b != 0) override def toString = s"$a / $b" val n = a val d = b def this(n:Int) = this(n, 1) def add(t:Rational) = if (d == t.d) new Rational(n + t.n,t.d) else new Rational(n * t.d + t.n * d, d * t.d) def * (t:Rational) = new Rational(n * t.n, d * t.d) def * (t:Int) = new Rational(n * t, d) def unary_- = new Rational(-n, -d) def + (t:Rational) = add(t) } object Rational { implicit def int2Rat(i:Int) = new Rational(i) } // 有理數應用測試 val r = new Rational(3, 5) //r: Rational = 3 / 5 -r //res0: Rational = -3 / -5 val rr = new Rational(4) //rr: Rational = 4 / 1 val rrr = rr * r //rrr: Rational = 12 / 5 rr * 4 //res1: Rational = 16 / 1 5 * rr //res2: Rational = 20 / 1