0

我正在使用 Visual Basic 编写一个程序,该程序将用户输入作为 1 到 99 的整数,然后告诉用户您需要为该数量补充多少 25 美分硬币、硬币、硬币和便士。我的问题是完全语义化的,我的算法并没有像我想象的那样工作。这是进行实际数学运算的代码,其中使用的变量已经声明

Select Case Input
    Case 25 to 99
        numQuarters = Input / 25
        remainder = Input Mod 25

        Select Case remainder

            Case 10 to 24
                numDimes = remainder / 10
                remainder = remainder mod 10
                numNickles = remainder / 5
                remainder = remainder mod 5

                numPennies = remainder

我将停在那里,因为这是代码中唯一给我带来麻烦的部分。当我输入一个从 88 到 99 的数字(由代码的那部分处理)时,数字会变得很奇怪。例如,88 给了我 4 个 25 美分、1 个硬币、1 个 Nickle 和 3 个便士。我不太确定发生了什么,但如果有人可以帮助我,我将不胜感激。

4

1 回答 1

0

我认为你的问题是它存储了除法的小数部分,当它应该删除它并只保留整数倍数时,因为每个硬币的小数部分反映在余数中。

因此,在每个除法之后,将其截断。例如:

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
于 2013-09-02T00:33:22.253 回答