VB 十进制转二进制 代码问题 急!!
Dim n As Integer, num As Long
Dim ch As String, Bin() As String, r As Integer, i As Integer
num = Val(Text1)
n = 0
Do
r = num Mod 2
n = n + 1
ReDim Bin(n)
Loop Until r = 0
For i = UBound(Bin) To 1 Step -1
ch = ch & Bin(i)
Next i
Text2 = ch
End Sub
哪里出了错?跪求高手帮忙修改! 展开
这样:
Private Sub Command1_Click()
Dim n As Integer, num As Long
Dim ch As String, Bin() As String, r As Integer, i As Integer
num = Val(Text1.Text)
n = 0
r = num
Do
n = n + 1
ReDim Preserve Bin(n)
Bin(n) = r Mod 2
r = r \ 2
Loop Until r < 1
For i = UBound(Bin) To 1 Step -1
ch = ch & Bin(i)
Next i
Text2.Text = ch
End Sub
redim数组变量没有给其赋值。
扩展资料:
注意事项
一个十进制转二进制的函数:
Public Function D2B(D As Integer) As String
D2B = ""
Do While D > 0
D2B = D Mod 2 & D2B
D = D \ 2
Loop
End Function
Private Sub Form_Load()
Me.Caption = D2B(8)
End Sub
另外的办法:
Function dToTwo(n As Integer) As String
Dim S As String
S = ""
Do While n <> 0
a = n Mod 2
n = n \ 2
S = Chr(48 + a) & S
Loop
dToTwo= S
End Function
r = Val(Text1)
n = 0
Do
ch = r Mod 2 & ch
r = r \ 2
Loop Until r = 0
Text2 = ch
End Sub
你redim 数组变量 却不给其赋值 不是白搭么
再者你若是要 动态REDIM 也要加Preserve 这样才可保留住之前的数据
redim Preserve bin(n)
再者 r = num Mod 2 永远都是初始值NUM 去求余 那R值不都永远一样么
要是Num是奇数 不就死循环了
如 100 转成2进制
用辗转相除法
100
除2 50 余数0
除2 25 余数0
除2 12 余数1
除2 6 余数0
除2 3 余数0
除2 1 余数1
除2 0 余数1
把相除过程中产生的余数倒序看 1100100 这就是100变成2进制的值
再看程序
Public Function DECtoBIN(Dec As Long) As String
DECtoBIN = ""
Do While Dec > 0 //这个循环就是辗转相除法的循环
DECtoBIN = Dec Mod 2 & DECtoBIN //DECtoBIN 是每次产生的余数连成的字符串
Dec = Dec \ 2 //dec为下次要进行除法的被除数。
Loop //注意这里字符串连接是倒序连接
End Function
同理看下面程序
Dim a%(10),m%,i%
M=val(inputbox(""))
i=0
do while m<>0 //这个也是辗转相除法的循环
a(i)=m mod 2 //用数组保留除得的余数
m=m\2 //m为下次要进行除法的被除数
i=i+1
loop
for k=i-1 to 0 step-1 //倒序输出余数
print a(k);
next
额,我不要其他方法。。。就想知道自己的方法哪里出错了
Private Sub Command1_Click()
Dim n As Integer, num As Long
Dim ch As String, Bin() As String, r As Integer, i As Integer
num = Val(Text1.Text)
n = 0
r = num
Do
n = n + 1
ReDim Preserve Bin(n)
Bin(n) = r Mod 2
r = r \ 2
Loop Until r < 1
For i = UBound(Bin) To 1 Step -1
ch = ch & Bin(i)
Next i
Text2.Text = ch
End Sub
2011-04-22
do while(n>2)
s=s & (n and 1)
n=n\2
loop
s=strreverse(s)
msgbox s