某城市的捷運車票共有20、25、30、35、40、45六種,而可投入的錢幣共有1、5、10、50、100元五種。
請計算可能的投幣方式與需找回的零錢金額。
(當所投入的金額超過票價後,多投的錢幣會直接吐還給使用者,所以,多投的部分不用計算。例如,票價20元,當依序投入7個1元、3個5元後,再來投入任何錢幣都會直接先吐還使用者。直接先吐還的這部分,不用寫入程式。)
輸入:in.txt
20
輸出:out.txt
投入20個1元,找回0元。
投入15個1元 1個5元,找回0元。
投入10個1元 2個5元,找回0元。
投入5個1元 3個5元,找回0元。
…
投入1個50元,找回30元。
投入1個100元,找回80元。
Private Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, a
For i5 = 1 To 10
For i10 = 1 To 10
If (i5 * 5 + i10 * 10) >= a And (i5 * 5 + i10 * 10) - a < 5 Then
If i5 = 0 Then ch ("投入" & i10 & "個10元,找回" & (i5 * 5 + i10 * 10) - a & "元"): Exit For
If i10 = 0 Then ch ("投入" & i5 & "個5元,找回" & (i5 * 5 + i10 * 10) - a & "元"): Exit For
Call ch("投入" & i5 & "個5元 " & i10 & "個10元,找回" & (i5 * 5 + i10 * 10) - a & "元")
End If
Next
Next
For i = 1 To 50
For i5 = 1 To 10
For i10 = 1 To 10
If i + i5 * 5 = a Then ch ("投入" & i & "個1元 " & i5 & "個5元,找回0元"): Exit For
If i + i10 * 10 = a Then ch ("投入" & i & "個1元 " & i10 & "個10元,找回0元"): Exit For
If i + i10 * 10 + i5 * 5 = a Then ch ("投入" & i & "個1元 " & i5 & "個5元 " & i10 & "個10元,找回0元"): Exit For
Next
Next
Next
Print #2, "投入1個50元,找回" & 50 - a & "元"
Print #2, "投入1個100元,找回" & 100 - a & "元"
Close
Close
End
End Sub
Sub ch(a)
AAA = 0
For i = 0 To List1.ListCount - 1
If a = List1.List(i) Then AAA = 1
Next
If AAA = 0 Then List1.AddItem a: Print #2, a
End Sub
Private Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, N
M(1) = 1
M(2) = 5
M(3) = 10
M(4) = 50
M(5) = 100
Call ABC(0, 0, 0, 0, 0, 0)
Close #2
Close #1
End
End Sub
Sub ABC(ByVal A, ByVal M1, ByVal M5, ByVal M10, ByVal M50, ByVal M100)
If A >= N Then
back = A - N
Do
p = False
If back >= 50 And M50 >= 1 Then back = back - 50: M50 = M50 - 1: p = True
Loop Until p = False
Do
p = False
If back >= 10 And M10 >= 1 Then back = back - 10: M10 = M10 - 1: p = True
Loop Until p = False
Do
p = False
If back >= 5 And M5 >= 1 Then back = back - 5: M5 = M5 - 1: p = True
Loop Until p = False
Do
p = False
If back >= 1 And M1 >= 1 Then back = back - 1: M1 = M1 - 1: p = True
Loop Until p = False
ans = "投入"
If M1 > 0 Then ans = ans & M1 & "個1元,"
If M5 > 0 Then ans = ans & M5 & "個5元,"
If M10 > 0 Then ans = ans & M10 & "個10元,"
If M50 > 0 Then ans = ans & M50 & "個50元,"
If M100 > 0 Then ans = ans & M100 & "個100元,"
ans = ans & "找回" & back & "元。"
p = False
For i = 0 To (List1.ListCount - 1)
If ans = List1.List(i) Then p = True
Next i
If p = False Then List1.AddItem ans: Print #2, ans
Else
If A < N Then Call ABC(A + M(1), M1 + 1, M5, M10, M50, M100)
If A < N Then Call ABC(A + M(2), M1, M5 + 1, M10, M50, M100)
If A < N Then Call ABC(A + M(3), M1, M5, M10 + 1, M50, M100)
If A < N Then Call ABC(A + M(4), M1, M5, M10, M50 + 1, M100)
If A < N Then Call ABC(A + M(5), M1, M5, M10, M50, M100 + 1)
End If
End Sub
arro、佑好,
回覆刪除你們的程式,都正確。
但是,arro,你還是用了之前說的多餘的迴圈太多。
要能學習前進,不能一直停在原地,加油。