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.5699997其实就是-1.57,浮点数存在精度误差,在四则运算中,这种误差会放大,从而结果尾数出现偏差。
你可以对结果加上四舍五入操作。