2010年3月23日 星期二

購買花朵


鬱金香一朵50元、香水百合一朵10元、白玫瑰一朵5元、滿天星一朵1元,現王先生有一筆金額N (0<100),請設計一程式,計算出此金額若全部用完,能買到的花朵數。(買到的花朵數必須為最少,花朵數若非最少,則本題算錯,零分計算。)

輸入說明:輸入金額n
輸入範例:假定先生有 78元。實際輸入之檔案內容如下:
實際輸入:(test2.txt)
78

輸出說明:第一列為花朵總數。第二列到第五列分別為鬱金香、香水百合、白玫瑰、滿天星的花朵數。
輸出範例:上例中先生有 78元,能買到最少的花朵數分別為鬱金香1朵、香水百合2朵白、玫瑰1朵、滿天星3朵。實際輸出之檔案內容如下:
實際輸出:(result2.txt)
                7
                1
                2
                1
                3

9 則留言:

  1. Dim ans(5) As Integer
    Dim aa(5) As Integer
    Private Sub Form_Load()
    Open App.Path & "/in.txt" For Input As #1
    Open App.Path & "/out.txt" For Output As #2
    Input #1, N
    aa(1) = 50: aa(2) = 10: aa(3) = 5: aa(4) = 1
    For i = 1 To 4
    ans(i) = N \ aa(i)
    N = N Mod aa(i)
    ans(0) = ans(0) + ans(i)
    Next i
    For i = 0 To 4
    Print #2, ans(i)
    Next i
    Close #2
    Close #1
    End Sub

    回覆刪除
  2. 高仔好,
    這題就是找零錢問題,只是用了奇怪的方式來敘述題目而已。
    解答正確。

    回覆刪除
  3. Private Sub Form_Load()
    Dim mon(4) As Integer, nummon(4) As Integer
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    mon(1) = 50: mon(2) = 10: mon(3) = 5: mon(4) = 1
    Input #1, x
    q = 1: ans = 0
    Do Until q = 5
    Do Until x < mon(q)
    x = x - mon(q)
    nummon(q) = nummon(q) + 1
    ans = ans + 1
    Loop
    q = q + 1
    Loop
    Print #2, ans
    For i = 1 To 4
    Print #2, nummon(i)
    Next i
    Close #1
    Close #2
    End Sub

    回覆刪除
  4. 阿揚好,
    程式OK。
    中間的那個do loop有些多繞了,還是用mod 和 \來得直接些。

    回覆刪除
  5. Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Dim a(4) As Integer, b(4) As Integer
    Input #1, x
    a(1) = 50: a(2) = 10: a(3) = 5: a(4) = 1
    For i = 1 To 4
    b(i) = x \ a(i)
    x = x - (x \ a(i)) * a(i)
    Sum = Sum + b(i)
    Next i
    Print #2, Sum
    For i = 1 To 4
    Print #2, b(i)
    Next i
    Close #2
    Close #1
    End Sub

    回覆刪除
  6. 阿瑋好,
    程式ok, 但是
    x = x - (x \ a(i)) * a(i)
    這行和
    x = x mod a(i)
    有什麼不同嗎?

    回覆刪除
  7. Dim va(4) As Integer
    Dim Ans As Integer
    Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, aaa
    Do
    Select Case aaa
    Case Is >= 50
    aaa = aaa - 50
    va(4) = va(4) + 1
    Ans = Ans + 1
    Case Is >= 10
    aaa = aaa - 10
    va(3) = va(3) + 1
    Ans = Ans + 1
    Case Is >= 5
    aaa = aaa - 5
    va(2) = va(2) + 1
    Ans = Ans + 1
    Case Is >= 1
    aaa = aaa - 1
    va(1) = va(1) + 1
    Ans = Ans + 1
    End Select
    Loop Until aaa = 0
    Print #2, Ans
    For i = 4 To 1 Step -1
    Print #2, va(i)
    Next i
    Close #1
    Close #2
    End Sub

    回覆刪除