码迷,mamicode.com
首页 > 其他好文 > 详细

scala-第六章-Rational

时间:2014-12-14 22:50:25      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   os   sp   java   on   2014   log   

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

函数重载。

操作符重载。

控制台输入。

私有函数。

隐式转换。


<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

标签:blog   io   ar   os   sp   java   on   2014   log   

原文地址:http://blog.csdn.net/rowanhaoa/article/details/41928915

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!