/** * Created by common on 17-4-3. */ object Rational { def main(args: Array[String]) {
var r1 = new Rational(1, 2) var r2 = new Rational(1) System.out.println(r1.toString) System.out.println(r1.add(r2).toString) var r3 = new Rational(2, 2) System.out.println(r3) System.out.println(r1 + r3) } }
class Rational(n: Int, d: Int) { //检查先决条件,不符合先决条件将抛出IllegalArgumentException require(d != 0) //最大公约数 private val g = gcd(n.abs, d.abs)
private def gcd(a: Int, b: Int): Int = { if (b == 0) a else gcd(b, a % b) }
//进行约分 val numer: Int = n / g val denom: Int = d / g