⑴分别将十进制数x,y转换为二进制,并将转换的每位二进制数存储到数组a,b中;如果两个二进制位数不相等,则位数较少的前面用“0”补足,使之a,b数组元素个数一致;
⑵取出数组a,b中下标相同的数组元素进行运算,若值相同,则结果为0,否则为1;
根据上述运算方法,示例如表所示。
变量 | 十进制 | 二进制 | ||||
x | 19 | 1 | 0 | 0 | 1 | 1 |
数组a | a(1) | a(2) | a(3) | a(4) | a(5) | |
y | 9 | 0 | 1 | 0 | 0 | 1 |
数组b | b(1) | b(2) | b(3) | b(4) | b(5) | |
x xor y | 1 | 1 | 0 | 1 | 0 |
小明编写了一个VB程序,功能如下:在文本框Text1、Text2中分别输入x、y的值,单击“异或”按钮Command1,程序对数据进行异或运算,并将结果显示在列表框List1中。
Function f(z As Integer) As String
'此程序段实现将十进制数z转换为二进制数f
Dim y As Integer
Do While z > 0
y = z Mod 2
z = ①
f = str(y) & f
Loop
End Function
Private Sub Command1_Click()
Dim x,y,k,m As Integer
Dim s1 As String, s2 As String, s3 As String
Dim a(15) As String, b(15) As String
x = Val(Text1.Text): y = Val(Text2.Text)
If x < y Then
m = x: x = y: y = m
End If
s1 = f(x): s2 = f(y) 's1表示x的二进制数,s2表示y的二进制数
k = Len(s1)
For i = 1 To k '将转换后的二进制数按位分别存储到数组a和b
a(i) = Mid(s1, i, 1)
If i <= Len(s2) Then
b(i) = Mid(s2, i, 1)
Else
'②
End If
Next i
S3=""
For i = 1 To k
If Then '③
s3 = "0" + s3
Else
s3 = "1" + s3
End If
Next i
List1.AddItem "异或结果是:" + s3
End Sub
① ② ③