Scala编程之分数的四则运算

       在前面一篇关于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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值