小张编写 VB 程序,实现如下功能:在前 100 个偶自然数中,计算恰好有四位为 1 的二进制数的个数, 如图所示,单击“计算”按钮 Command1,在文本框 Text1 中显示符合条件的个数,在列表框 List1 中显示符合条件的二进制数。VB 程序代码如下:
提示:本题“除 2 取余倒排法”的方法将十进制转化为二进制,算法如下: 例如十进制数“97”转化为二进制的过程如右图所示:
因此“97”二进制值为:1100001
Dim a As Integer, c As Integer, w As Integer, i As Integer
Dim s As String, k As String
c = 0
For m = 1 To 100
k = ""
i = 2 * m
Do While i > 0
a=i Mod 2
k = str(a) + k
Loop
For n = 1 To Len(k)
s = Mid(k, n, 1)
If s = "1" Then w = w + 1
Next n
If w = 4 Then
c = c + 1
End if
Next m
Text1.Text = Str(c) End Sub