试题

试题 试卷

logo

题型:单选题 题类:常考题 难易度:困难

算法与程序设计

有如下VB程序段:

s=″72186345945″:c=0

For i=1 To 6

a(i)=Mid(s,i,i)

Next i

For i=1 To 4 Step 2

k=i

For j=i+2 To 6 Step 2

If a(j)<a(k) Then k=j

Next j

If k<>i Then

t=a(i):a(i)=a(k):a(k)=t:c=c+1

End If

Next i

Text1.Text=Str(c)

该程序段运行后,Text1中显示的内容是(  )

A、1 B、2 C、3 D、4
举一反三
编写VB程序,实现如下功能: 单击“排序数组a”按钮Command1时,对已有数组a的数据进行升序排列,并显示在文本框Label1中;单击“显示数组b”按钮Command2时,将升序数组b的数据显示在文本框Label2中;再单击“合并a和b”按钮Command3时,对数组a和数组b升序合并到字符串中,将合并后的数据在文本框Label3中显示。(运行效果如图所示)。实现上述功能的VB代码如下, 请在划线处填入合适代码。

Dim a(1 To 6) As Integer  

Dim b(1 To 6) As Integer

Private Sub Command1_Click()     '对数组a中的数据进行排序

Dim i As Integer, j As Integer ,k as integer

a(1) = 53 :a(2) = 18:a(3) = 62:a(4) = 22:a(5) = 6:a(6) = 25

s = ""

For i = 1 To 5

    k = i

    For j = i + 1 To 6

        If a(k) > a(j) Then {#blank#}1{#/blank#}

    Next j

    If i <> k Then

        t = a(k): a(k) = a(i): a(i) = t

    End If

Next i

For i = 1 To 6

    s = s + Str(a(i))

Next i

Label1.Caption = s

End Sub

Private Sub Command2_Click() 

b(1) = 3: b(2) = 8: b(3) = 15: b(4) = 27: b(5) = 38: b(6) = 49

'此处部分代码省略

End Sub

Private Sub Command3_Click()  

'将数组a和b中的数据逐个比较后添加到新的字符串s中,并将s在label3中显示

i = 1: j = 1: s = ""

Do While i <= 6 {#blank#}2{#/blank#}j <= 6           '如果两数组都还有数据未合并

    If  {#blank#}3{#/blank#}Then

        s = s + Str(a(i)) : i = i + 1

    Else

        s = s + Str(b(j)) : j = j + 1

    End If

Loop

Do While i <= 6                            '只有数组a还有数据未合并

    s = s + Str(a(i)) : i = i + 1

Loop

Do While j <= 6                            '只有数组b还有数据未合并

    s = s + Str(b(j)) : j = j + 1

Loop

Label3.Caption = s

End Sub

【加试题】字符串排序。编写VB程序,实现如下功能:程序运行时,单击命令按钮Command1 产生100个随机字符串(每个字符串长度不超过10),并显示在列表框List1中,单击命令按钮Command2对产生的100个随机字符串按权值进行降序排序,将排序结果显示在列表框List2中。每个字符串的权值定义为该字符串中ASCII码值最大的字母的ASCII码值,例如字符串“Hello”中ASCII码值最大的字母是“o”(ASCII码值为111),则字符串“Hello”的权值为111。程序运行效果如图所示。实现上述功能的VB代码如下,但加框处代码有错,请改正。

Dim a(1 To 100) As String '依次存放100 个随机字符串

Dim b(1 To 100) As Integer '依次存放每个字符串的权值

Private Sub Command1_Click() '产生100 个随机字符串

Dim i As Integer, k As Integer, t As Integer, x As Integer

Randomize

For i = 1 To 100

k = Int(Rnd * 10 + 1) : t = 0  'k 表示第i 个字符串的长度

Do While t < k '通过循环依次产生第i 个字符串a(i)的k 个字符

If Int(Rnd * 2 + 1) = 1 Then '产生一个小写字母的ASCII 码值

x = Asc("a") + Int(Rnd * 26)

Else

x = Asc("A") + Int(Rnd * 26) '产生一个大写字母的ASCII 码值

End If

                '①

If b(i) < x Then b(i) = x

t = t + 1

Loop

List1.AddItem a(i)

Next i

End Sub

Private Sub Command2_Click() '对100 个字符串按字符串权值降序排序

Dim i As Integer, j As Integer, y As Integer

Dim s As String

For i = 1 To 99

k = i

For j = i + 1 To 100

    '②

Next j

If k <> i Then

s = a(k): a(k) = a(i): a(i) = s

y = b(k): b(k) = b(i): b(i) = y

End If

Next i

For i = 1 To 100

List2.AddItem a(i)

Next i

End Sub

①{#blank#}1{#/blank#} ②{#blank#}2{#/blank#} 

返回首页

试题篮