刚学习VB没有多久..1.“约瑟夫(Josephus)问题”:设n个人围坐在一个圆桌周围,现在从第s个人开始报数,数到第m个人,让他出局;然后从出局的下一个人重新开始报数,数到第m个人,再让他出局,……,如此反复直到所有的人全部出局为止。试编写一个求解约瑟夫问题的过程,用整数序列1, 2, 3, ……, n表示顺序围坐在圆桌周围的人,并采用数组表示作为求解过程中使用的数据结构。下面是我写的程序.大家看看错误在哪里??
Option Explicit
Option Base 1
Private Sub Command1_Click()Dim n As Integer
Dim s As Integer
Dim m As Integer
Dim x As Integer
Dim p As Integer
Dim people() As Integer
If ((Text1.Text = "") Or (Text2.Text = "") Or (Text3.Text = "")) Then
        Picture1.Print "输入的数值度不能为空!"
        Exit Sub
End If
n = Text1.Text '9
s = Text2.Text '1
m = Text3.Text '5
p = s          '1
Picture1.Cls
ReDim people(n + 1) As Integer '10
For x = 1 To n       '9
    people(x) = x    '1----9
Next x
For x = 1 To n       '9
    p = p + m - 1    '5
    If (p > n) Then
        p = p - n
    End If
    Picture1.Print people(p)
    p = p + 1
Next x
End Sub

解决方案 »

  1.   

    输入n = 9, s = 1, m = 5 时,出局顺序为:
        5 1 7 4 3 6 9 2 8
      

  2.   

    错在已出圈的人你还在让他报数仅仅让 p = p + m - 1 是不行的, 在 p = p + m - 1 之前, 你得让people(p)从people数组中消失
      

  3.   

    修改如下:Option ExplicitOption Base 1Private Sub Command1_Click()
        Dim n As Integer
        Dim s As Integer
        Dim m As Integer
        Dim x As Integer
        Dim i As Integer
        Dim p As Integer
        Dim people() As Integer
        If ((Text1.Text = "") Or (Text2.Text = "") Or (Text3.Text = "")) Then
                Picture1.Print "输入的数值度不能为空!"
                Exit Sub
        End If
        n = Text1.Text
        s = Text2.Text
        m = Text3.Text
        p = s
        Picture1.Cls
        ReDim people(n + 1) As Integer
        For x = 1 To n
            people(x) = x
        Next x
        For x = 1 To n
    '        p = p + m - 1
    '        Do While (p > n)
    '            p = p - n
    '        Loop
            '下面的这行与上面的四行等效
            p = (p + m - 2) Mod n + 1
            Picture1.Print people(p)
            For i = p + 1 To n + 1
                people(i - 1) = people(i)
            Next i
            ReDim Preserve people(n) As Integer
            n = n - 1
        Next x
    End Sub