weixin_38920641
2020-09-09 22:20
采纳率: 66.7%
浏览 199

scala 运行结果中浮点数显示问题

  1. 下面一段代码中,其中第二个打印项显示结果为$-1.5699997,其实应该显示 为$-1.57才对,麻烦告知下原因,并帮助修改下代码以显示正确结果。
object quick1104 extends App {
  class Money(var dollar:Int,var cent:Int){
      def +(that:Money):Money={
        var a=((this.dollar+this.cent.toFloat/100)+(that.dollar+that.cent.toFloat/100)).toString.split("\\.")
        new Money(a(0).toInt,a(1).toInt)
      }
      def -(that:Money):Money={
        var a=((this.dollar+this.cent.toFloat/100)-(that.dollar+that.cent.toFloat/100)).toString.split("\\.")
        new Money(a(0).toInt,a(1).toInt)
      }
    def <(that:Money):Boolean= if((this.dollar+this.cent.toFloat/100)-(that.dollar+that.cent.toFloat/100)<0) true
    else
      false


  def ==(that:Money):Boolean=if((this.dollar+this.cent.toFloat/100)-(that.dollar+that.cent.toFloat/100)==0) true
  else
    false

    override def toString:String=s"$$$dollar.$cent"
  }

  var aa=new Money(10,4)
  var bb=new Money(11,61)
  var cc=new Money(11,61)
  println(aa+bb)
  println(aa-bb)
  println(aa<bb)
  println(cc==bb)
}


显示结果截图:
图片说明

1条回答 默认 最新

相关推荐 更多相似问题