16.小吳為了探究冒泡排序過程中數據的“移動”情況,編寫了一個VB程序,功能如下:在列表框List1中顯示排序前數據(存儲在數組a中),在文本框Text1中輸入初始位置(即下標值),單擊“排序”按鈕Command1后,在標簽Label1中顯示指定初始位置的數據在排序過程中的位置變化情況,排序后的數據顯示在列表框List2中。程序運行界面如圖所示。 實現上述功能的VB程序如下,但加框處代碼有錯,請改正。 Dim a(1To 8)As Integer Dim n As Integer Private Sub Form_Load ( ) 'n=8,排序前的8個數據存儲在數組a中,并在列表框Listl中顯示 '代碼略 End Sub Private Sub Command1_Click ( ) Dim i As Integer,j As Integer,k As Integer Dim pos As Integer'變量pos存儲指定數據的位置(即下標值) Dim s As String'變量s存儲pos變化情況 s=Text1.Text pos=Val(Text1.Text) For i=1To n-1 For j=n To i+1Step-1 If a(j)<a(j-1)Then ‘(1) a(j-1)=a(j) a(j)=k '如果pos位置的數據參與交換,則更新pos值,記錄pos變化情況 If pos=j Then pos=j-1 s=s+”→”+Str(pos) ‘(2) pos=j s=s+”→”+Str(pos) End If End If Next j Next i Label1.Caption=”位置變化情況:”+s For i=1To n List2.AddItem Str(a(i)) Next i End Sub
(2)請在橫線處填入合適的代碼。 Private Sub Command1_Click ( ) Dim s As String,ch As String Dim ans As String Dim a(1To 3)As Integer'用于存儲RGB 對應的3 個分量 Dim i As Integer,j As Integer s=Text1.Text s=Mid(s,5,Len(s)-5)'取出括號內的字符串 i=1:j=1 Do While i<=Len(s) ch=Mid(s,i,1) If ch>=“0“And ch<=“9“Then a(j)=①
Else j=j+1 End If i=i+1 Loop For i=1To 3 ②
Next i Label1.Caption=“#“+ans End Sub Function btoh(x As Integer) As String'將十進制數轉換成兩位十六進制數 Const zf=“0123456789ABCDEF“Dim r As Integer,h As String h=““ Do While x>0 r=x Mod 16 h=Mid(zf,r+1,1)+h x=x\16 Loop If Len(h)=1Then h=“0“+h If Len(h)=0Then h=“00“ ③