2012年11月20日 星期二

天平秤重

有一天平,共有四個法碼,分別為1、3、9、27公克。請設計一程式,由"in.txt"輸入某一物品質量(1~40公克)。


輸入範例:
8公克


輸出範例:
左盤1公克,右盤9公克

2 則留言:

  1. Dim number(4), leftt, right As Integer
    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, leftt
    ori = leftt
    number(1) = 1: number(2) = 3: number(3) = 9: number(4) = 27
    Do
    For i = 4 To 1 Step -1
    If leftt = right Then Exit For
    If Abs(leftt - right) * 2 > number(i) And leftt > right Then right = right + number(i)
    If Abs(leftt - right) * 2 > number(i) And right > leftt Then leftt = leftt + number(i)
    Next
    Loop Until leftt = right
    Print #2, "左盤" & leftt - ori & "公克" & "," & "右盤" & leftt & "公克"
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  2. Dim num()
    Dim s, lt, rt, x As Integer
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    num = Array(1, 3, 9, 27)
    Input #1, x
    lt = 0: rt = 0: s = x
    Do
    For i = 3 To 0 Step -1
    If Abs(s - num(i)) < s And x > rt Then rt = rt + num(i): s = Abs(s - num(i))
    If Abs(s - num(i)) < s And x < rt Then lt = lt + num(i): s = Abs(s - num(i))

    Next i
    Loop Until rt - lt = x
    Print #2, "左盤" & lt & "公克,右盤" & rt & "公克"
    Close #2
    Close #1
    End
    End Sub

    回覆刪除