Visual Basic更改制造商计划

时间:2013-09-01 18:47:16

标签: algorithm vba

我正在使用Visual Basic中的一个程序,该程序将用户输入作为1到99之间的整数进行处理,然后告诉您使用该数量需要补充多少个季度,硬币,镍币和便士。我的问题是完全合乎逻辑的,我的算法不像我想的那样工作。下面是执行实际数学的代码,其中使用的变量已经声明为

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个四分之一,1个角钱,1个镍币和3个便士。我不太确定发生了什么,但如果有人能帮助我,我会很感激。

1 个答案:

答案 0 :(得分:0)

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

所以在每次除法之后,截断它。 E.g:

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

无论如何,pehaps是一种更灵活的方式,它不依赖于硬编码的优先顺序,可以处理你喜欢的任何单位(美分,分数美元,等等):

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