例如n=8,k=6,则依次出圈的猴子的编号为6、4、3、5、8、7、2,最后剩下的猴子的编号为1,即猴子大王的编号为1。
程序运行时,在文本框Text1中输入猴子的总数n,单击“产生随机数k”按钮Command1将生成一个随机整数k(1≤k≤n),并在标签 Label3中显示k的值,单击“选大王”按钮Command2后,将在文本框Text2中显示依次出圈的猴子的编号,在标签Label6中显示猴子大王的编号。程序运行结果如图所示。
实现上述功能的VB程序如下,请在划线处填入合适的代码。
Dim k As Integer, n As Integer
Private Sub Command1_Click ( )
Randomize
n= Val(Text1. Text)
k = Int (Rnd n) + 1
Label3. Caption Str(k)
End Sub
Private Sub Command2_Click ( )
Dim a (1 To 100) As Integer ‘a(i) = 1 表示编号为i的猴子在圈上,a(i) = 0表示出圈
Dim b (1 To 100) As Integer ‘ 数组元素b(i)=x,表示第i只出圈的猴子的编号为x
Dim i As Integer, st As String, j As Integer
Dim p As Integer, sum As Integer ‘ p表示出圈的猴子数,sum表示报数的数值
For i = 1 To n
a(i) = 1
Next i
p = 0
j = 0
Do While p <> n-1
①
Do While sum < k ‘ 依次报数,直到报到k为止
j=j+1
If j > n Then j = 1 ‘ 报数至最后时,将重头继续报
sum = sum + a(j)
Loop
a(j) = 0: p =p+1
②
Loop
For i=1 To p
st= st str(b(i)
Next i
Text2. Text = st
i=1
Do While a(i) <> 1
i=i+1
Loop
Label16. Caption = ③
End Sub
① ② ③