在前面一篇关于Scala编程的文章中简单的介绍了Scala语言,关于Scala语言的一些语法及规则,如有感兴趣的朋友可以自己阅读相关书籍,鄙人诚挚推荐《Scala In Programming》,下面利用Scala语言实现简单的分数四则运算。
1、分数的四则运算类
class Rational(n: Int,d: Int) { //分母不能为0的校验 require(d != 0) //分数的最简形式 private val simple = gcb(n.abs,d.abs) val numer = n / simple val denom = d / simple //从构造器(分母为1) def this(n: Int) = this(n,1) //加 def +(that: Rational) : Rational = new Rational( numer * that.denom + that.numer * denom, denom * that.denom ) def +(i: Int) : Rational = new Rational( numer + i * denom, denom ) //减 def -(that: Rational) : Rational = new Rational( numer * that.denom - that.numer * denom, denom * that.denom ) def -(i: Int) : Rational = new Rational( numer - i * denom, denom ) //乘 def *(that : Rational) : Rational = new Rational( numer * that.numer, denom * that.denom ) def *(i: Int) : Rational = new Rational( numer * i, denom ) //除 def /(that: Rational) : Rational = new Rational( numer * that.denom, denom * that.numer ) def /(i: Int) : Rational = new Rational( numer, denom * i ) private def gcb(a:Int,b:Int) : Int = { if(b == 0) a else gcb(b,a%b) } override def toString = numer + "/" + denom }
2、测试用例
object RationalDemo extends App{ val oneHalf = new Rational(1,2) val twoHalf = new Rational(3,4) val sum = oneHalf + twoHalf val sub = oneHalf - twoHalf val mul = oneHalf * twoHalf val div = oneHalf / twoHalf println("oneHalf + twoHalf = " + sum) println("oneHalf - twoHalf = " + sub) println("oneHalf * twoHalf = " + mul) println("oneHalf / twoHalf = " + div) }
3、测试结果
oneHalf + twoHalf = 5/4
oneHalf - twoHalf = -1/4
oneHalf * twoHalf = 3/8
oneHalf / twoHalf = 2/3