Dim y As String
Dim a(-32768 To 32767) As Integer
Dim h(-32768 To 32767) As Integer
Dim s As Integer
Dim k As String
Dim p As Single
Dim x As String
Private Sub Command1_Click()
k = \"\"
x = \"\"
s = Text1.Text
s = Abs(Fix(s))
i = -32768
p = Text1.Text
p = Abs(p - Fix(p))
j = -32768
Do While Not s = -1
If s >= 2 Then
a(i) = s Mod 2
s = s \\ 2
k = a(i) & k
i = i + 1
ElseIf s = 1 Then
k = 1 & k
s = -1
ElseIf s = 0 Then
k = 0 & k
s = -1
End If
Loop
Do While Not p = Fix(p)
If 0 <= p < 1 Then
p = p * 2
If p >= 1 Then
h(j) = 1
x = x & h(j)
p = p - 1
j = j + 1
Else
h(j) = 0
x = x & h(j)
j = j + 1
End If
End If
Loop
If k = \"\" Then
k = 0
End If
If x = \"\" Then
x = 0
End If
If Text1.Text > 0 Then
y = k & \".\" & x
ElseIf Text1.Text < 0 Then
y = \"-\" & k & \".\" & x
ElseIf Text1.Text = 0 Then
y = \"0\" & \".\" & \"0\"
End If
Label1.Caption = y
End Sub
我在執行的時候假設Text1.text為3.5
他卻會顯示100.1 會自動在整數部分+1
若輸入為3.25
卻很正常的印出 11.01
各位大大可以幫我看看我寫的這段程式碼,有什麼問題嗎?
2006-02-06 17:21:04 · 1 個解答 · 發問者 jsgao0 2 in 電腦與網際網路 ➔ 程式設計
你把S宣告成Single應該就可以了^^
Dim s As Integer改成Dim s As Single,因為s為整數的話 Text1=3.5,s=Text1 →S=4,所以答案就錯誤了XD
一時手癢也寫了一段來玩玩,請測試一下..Orz
Private Sub Command1_Click()
Print "十進制:"; Text1.Text
Print "二進制:"; TTo2(Text1.Text, 10) '10代表取小數點後10位,預設為20位
End Sub
Function TTo2(ByVal N As Single, Optional ByVal P As Integer = 20) As String
Dim S As String, B As String, T As Single, nN As Single
'記錄正負數
If InStr(N, "-") Then B = "-": N = Replace$(N, "-", "")
nN = Fix(N)
'處理整數部分
Do
TTo2 = nN Mod 2 & TTo2: nN = nN \ 2
Loop Until nN = 0
'處理小數部分
If InStr(N, ".") And P > 0 Then
nN = N - Fix(N): T = 0.5
Do
S = S & -1 * Int(nN - T >= 0)
If nN = T Then Exit Do
If nN > T Then nN = nN - T
T = T / 2
Loop Until Len(S) = P
S = Mid$(S, 1, InStrRev(S, "1")) '除掉小數後方多於的 0
If Len(S) Then S = "." & S
End If
TTo2 = B & TTo2 & S
End Function
2006-02-06 20:47:03 · answer #1 · answered by W.J.S. 7 · 0⤊ 0⤋