1. 程式人生 > >Scala第一個Demo(大專案的一塊磚)

Scala第一個Demo(大專案的一塊磚)

package com.leep.scala

/**

 * 定義有理數類,並完成加減乘除運算

 */

class Rational (n:Int,d:Int){

  require(d!=0) // 分母不為零

  private val g=gcd(n.abs,d.abs) //最大公約數

  val number = n/g

  val denom = d/g

  def this(n:Int) = this(n,1) //輔助構造器

  def + (that: Rational) :Rational =

    new Rational (number * that.denom+that.number * denom,

        denom * that.denom

        )

  def + (i: Int): Rational =

    new Rational(number + i*denom,denom)

  def -(that:Rational) =

    new Rational(

        number * that.denom - that.number * denom,

        denom * that.denom

        )

  def - (i:Int): Rational =

    new Rational(number - i * denom, denom)

  def * (that: Rational) : Rational =

    new Rational (number * that.number, denom * that.denom)

  def * (i: Int) : Rational =

    new Rational (number * i,denom)

  def / (that: Rational) :Rational =

    new Rational (number * that.denom, denom * that.number)

  def / (i : Int) : Rational =

    new Rational(number, i * denom)

  override def toString = number + "/" + denom //過載 toString 方法

  /**

   * 計算兩個數的最大公約數

   * 用到遞迴

   */

  private def gcd(a:Int,b:Int) : Int = {

    if (b==0)

      a

    else

      gcd(b,a%b)

  } 

}

/**

 * 半身物件,這裡主要為測試用

 */

  object Rational{

    def main(args: Array[String]): Unit = {

      val rl = new Rational(1,2);

      println(rl)

      val rs = rl+ new Rational(1);

      println(rs)

    }

  }