首页 > 代码库 > scala-第六章-Rational

scala-第六章-Rational

涉及到的知识点:
检查先决条件。

函数重载。

操作符重载。

控制台输入。

私有函数。

隐式转换。


<pre name="code" class="java">import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
class Rational(n:Int, d:Int){
  require(d != 0);//检查先决条件
  
  private val g = gcd(n.abs, d.abs);
  val num: Int = n / g;
  val den: Int = d / g;
  
  override def toString = n +"/"+ d;//重载tosting
  def this(n: Int) = this(n, 1);
  
  def +(that: Rational): Rational = //定义操作符号
    new Rational(
    	num * that.den + that.num * den,
    	den * that.den
    )
  def *(that: Rational): Rational =
    new Rational(num * that.num, den * that.den)
  def *(i: Int): Rational = //重载*
    new Rational(i*num, den)
  
  def lessThan(that: Rational) = 
    this.num * that.den < that.num * this.den
  def max(that: Rational) =
    if(this.lessThan(that)) that else this
  private def gcd(n: Int, d:Int): Int =//私有函数
    if(d==0) n else gcd(d, n%d)
}
object Rational {
  def main(args: Array[String]){
    var bf = new BufferedReader(new InputStreamReader(System.in));
    var line = bf.readLine();
    var eles = line.split(" ")
    val R1 = new Rational(Integer.parseInt(eles(0)), Integer.parseInt(eles(1)));
    line = bf.readLine();
    eles = line.split(" ");
    val R2 = new Rational(Integer.parseInt(eles(0)), Integer.parseInt(eles(1)));
    val R3 = R1 + R2;
    val R4 = new Rational(2);
    implicit def intToRational(x: Int) = new Rational(x)//隐式转换
    //隐式转换要放在作用域,而不是放在类内!
    val R5 = 2 * R3;
    println(R5);
  }
}




scala-第六章-Rational