我认为你的问题是它存储了除法的小数部分,当它应该删除它并只保留整数倍数时,因为每个硬币的小数部分反映在余数中。
因此,在每个除法之后,将其截断。例如:
numQuarters = Int(Input / 25)
remainder = Input Mod 25
'or since you aren't working with fractional currencies you could use integral division operator '\':
numQuarters = Input \ 25
使用 88 作为输入,在这些行之后,numQuarters = 3 和剩余 = 18
无论如何,也许是一种更灵活的方式,它不依赖于硬编码的优先顺序,并且可以处理您喜欢的任何单位(美分、小数美元等),例如:
Sub exampleUsage()
Dim denominations, change
Dim i As Long, txt
'basic UK coins, replace with whatever
'you can of course use pence as the unit, rather than pounds
denominations = Array(1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01)
change = ChaChing(3.78, denominations)
For i = 0 To UBound(denominations)
txt = txt & Format(denominations(i), "£0.00") & " x " & change(i) & " = " & Format(denominations(i) * change(i), "£0.00") & vbCrLf
Next i
MsgBox (txt)
End Sub
'denominations is a Vector of valid denominations of the amount
'the return is a Vector, corresponding to denominations, of the amount of each denomination
Public Function ChaChing(ByVal money As Double, denominations)
Dim change, i As Long
ReDim change(LBound(denominations) To UBound(denominations))
For i = LBound(denominations) To UBound(denominations)
If money = 0 Then Exit For 'short-circuit
change(i) = Int(money / denominations(i))
money = money - change(i) * denominations(i)
Next i
ChaChing = change
End Function