2012年1月16日 星期一

化成二進位

數字(0~127)

n → 化成二進位 →加上偶同位→換算值

輸入→化成二進位→加上偶同位→換算成十進位→輸出

3 → (0000011) 2 → (00000110) 2 → 6

100 → (1100100) 2 → (11001001) 2 → 201

4 則留言:

  1. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Dim s(8), g(8) As Integer
    Input #1, x

    For i = 1 To x
    s(i) = x Mod 2
    x = x \ 2
    A = i
    If x = 0 Then Exit For
    Next
    For i = A To 1 Step -1
    ans = ans & s(i)
    Next
    '------------------
    a1 = Len(ans)
    n = 0
    For i = 1 To a1
    s(i) = Mid(ans, i, 1)
    If s(i) = 1 Then n = n + 1
    Next
    If n Mod 2 = 0 Then
    ans = ans & 0
    Else
    ans = ans & 1
    End If
    '--------------------------
    a1 = Len(ans)
    ans1 = 2
    For i = 2 To (a1)
    g(i) = Mid(ans, i, 1)
    ans1 = ans1 + g(i)
    If (b + 1) = a1 Then Exit For
    ans1 = ans1 * 2
    b = i
    Next
    Print #2, ans1
    Close
    Close
    End
    End Sub

    回覆刪除
  2. 小冰好,
    這題正確。
    當然,這樣將程式分成三等分,是清楚的,用於教學超適合。
    但是,寫完這樣的第一版後,第二版,是可以將三個部分,合成一次完成的。
    在分成2進位時,就可以算有幾個1。
    那原來的2進位輸出時,再來就可以輸出偶同位,然後,這個2進位的值,直接是原來的數,乘上(?),再加上(?),就是了吧。

    回覆刪除
  3. 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, x
    Sum = 0: y = 0
    ' (Q:0~127)
    Do Until x = 0
    y = x Mod 2
    If y = 1 Then Sum = Sum + 1
    ans = y & ans
    x = x \ 2
    Loop
    Do Until Len(ans) = 7
    ans = 0 & ans
    Loop
    If Sum Mod 2 = 0 Then
    ans = ans & 0
    Else
    ans = ans & 1
    End If
    a = Len(ans)
    b = 0
    c = a - 1
    For i = 1 To a
    b = b + Mid(ans, i, 1) * 2 ^ c
    c = c - 1
    Next i
    Print #2, b
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  4. Private Sub Form_Load()
    Dim arr()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, n
    s = n
    Do Until n <= 1
    n = n \ 2
    s = s Mod 2
    g = s & g
    Loop
    yiqi = n & g
    If Len(yiqi) < 7 Then y = 7 - Len(yiqi)
    For i = 1 To y
    zero = zero & "0"
    Next i
    yiqi = zero & yiqi
    For i = 1 To Len(yiqi)
    one = Mid(yiqi, i, 1)
    If one = 1 Then sumA = sumA + 1
    Next i
    If sumA Mod 2 <> 0 Then
    yiqi = yiqi & "1"
    Else
    yiqi = yiqi & "0"
    End If
    ReDim arr(Len(yiqi))
    For i = 1 To Len(yiqi)
    arr(i) = Mid(yiqi, i, 1)
    Next i
    zz = -1
    For i = Len(yiqi) To 1 Step -1
    zz = zz + 1
    Sumnum = Sumnum + arr(i) * (2 ^ zz)
    Next i
    Print #2, Sumnum
    Close #1
    Close #2
    End
    End Sub

    回覆刪除