使用Scala Int和Double数据类型计算不正确

时间:2016-12-03 18:19:49

标签: scala

我正在编写一个简单的函数来计算一袋硬币的价值。它消耗了四个数字:包中的便士,镍币,硬币和四分之一;它会产生足够的钱。

这是功能:

scala> def sum_coins(penny:Int=0, nickel:Int=0, dime:Int=0, quarter:Int=0) = { penny * (0.01) + nickel * 0.05 + dime * 0.1 + quarter * 0.25 }

为什么结果看起来像这样?

scala> sum_coins(1,1,1,1)
res13: Double = 0.41000000000000003

我希望结果应该是0.41

2 个答案:

答案 0 :(得分:0)

文字0.010.050.10.25默认为浮点Double,您应该使用BigDecimal。以下实现使用BigDecimal代替。

trait Money{
  def amount:BigDecimal
}
case class Dollar(override val amount: BigDecimal) extends Money{
  def +(d:Dollar):Dollar = Dollar(this.amount + d.amount)
}
case class Penny(override val amount: BigDecimal) extends Money
case class Nickel(override val amount: BigDecimal) extends Money
case class Dime(override val amount: BigDecimal) extends Money
case class Quarter(override val amount: BigDecimal) extends Money

implicit def pennyToDollar(p: Penny):Dollar = Dollar(p.amount * BigDecimal(0.01))
implicit def nickelToDollar(n: Nickel):Dollar = Dollar(n.amount * BigDecimal(0.05))
implicit def dimeToDollar(d: Dime):Dollar = Dollar(d.amount * BigDecimal(0.1))
implicit def quarterToDollar(q: Quarter):Dollar = Dollar(q.amount * BigDecimal(0.25))


def sumCoins(penny:Int=0, nickel:Int=0, dime:Int=0, quarter:Int=0):Dollar = {
  Penny(penny) + Nickel(nickel) + Dime(dime) + Quarter(quarter)
}

sumCoins(1,1,1,1) //Dollar(0.41)

答案 1 :(得分:0)

这是微不足道的双重“问题”

对于确切的数字,如金钱,请使用BigDecimal,正如D先生提议的那样。

def sum_coins(penny:Int=0, nickel:Int=0, dime:Int=0, quarter:Int=0) = 
 penny * BigDecimal(0.01) + 
 nickel * BigDecimal(0.05) + 
 dime * BigDecimal(0.1) + 
 quarter * BigDecimal(0.25)