一个我似乎无法发现的错误。错误的逻辑?

时间:2011-09-08 19:47:58

标签: vba

问题描述: 抬起一堆硬币。翻转最顶层的硬币,放回堆叠然后继续:将前2个硬币作为单个堆叠取出(尾部,头部朝上翻转并放回堆叠尾部,头部(两个硬币翻转就像胶合一样)一起))。现在以相同的方式翻转前3个硬币并放回堆叠(你得到:尾巴,尾巴,头部(如果有4个硬币,那将是尾巴,尾巴,尾巴,头部)。当你翻转整个堆叠用第一枚硬币再次开始。继续,直到你回到所有抬头的堆叠。

(希望很清楚)

有人能看出为什么这个小程序会失败吗?对我来说,我第一次注意到错误的例子是当计数达到18时,堆叠了6个硬币。

为了运行代码:

  • 当前选定的WorkSheet必须命名为“Sheet3”
  • <活动工作表上的
  • ,输入C1单元格中的硬币数量。
  • 运行FlippingCoins()方法

代码:

Sub FlippingCoins()
    Call theStackOfCoins
    Call theFlipping
End Sub


Sub theStackOfCoins()
Worksheets("Sheet3").Cells(1, 3).Select
Columns("A:b").Select
Selection.ClearContents
Range("a3").Select

Dim StackOfCoins As Integer
    StackOfCoins = Worksheets("Sheet3").Cells(1, 3).Value

Dim Flip_x_coins As Integer
    Flip_x_coins = 0

Dim row As Integer
    row = 0

For theStack = 1 To StackOfCoins
    Worksheets("Sheet3").Cells(row + theStack, 1).Value = True
Next theStack

End Sub

Sub theFlipping()

Dim middleCoin As Integer
    middleCoin = 0
Dim passes As Integer
    passes = 0
Dim Fst As Integer
    Fst = 0
Dim Lst As Integer
    Lst = 0

Dim stack As Integer
    stack = Worksheets("Sheet3").Cells(1, 3).Value

Dim count As Integer
    count = 0

Dim Finished As Boolean
    Finished = False

Reset:
    Flip_x_coins = 1
For Flip_x_coins = 1 To stack
    Worksheets("Sheet3").Cells(1, 4).Value = Flip_x_coins
    count = count + 1
    If Flip_x_coins = 1 Then
        Worksheets("Sheet3").Cells(1, 1).Value = Not (Worksheets("Sheet3").Cells(1, 1).Value)
    Else
        passes = Int(Flip_x_coins) / 2
        Fst = 1
        Lst = Flip_x_coins
        For pass = 1 To passes
            If Worksheets("Sheet3").Cells(Fst, 1).Value = Worksheets("Sheet3").Cells(Lst, 1).Value Then
                    Worksheets("Sheet3").Cells(Fst, 1).Value = Not (Worksheets("Sheet3").Cells(Fst, 1).Value)
                    Worksheets("Sheet3").Cells(Lst, 1).Value = Not (Worksheets("Sheet3").Cells(Lst, 1).Value)
            End If
            Fst = Fst + 1
            Lst = Flip_x_coins - 1
        Next pass
        If Flip_x_coins Mod 2 > 0 Then
            middleCoin = (Flip_x_coins + 1) / 2
            Worksheets("Sheet3").Cells(middleCoin, 1).Value = Not (Worksheets("Sheet3").Cells(middleCoin, 1).Value)
        End If
    End If
    For testComplete = 1 To stack
        If Worksheets("Sheet3").Cells(testComplete, 1).Value = False Then
            Finished = False
            Exit For
        Else
            Finished = True
        End If
    Next testComplete
    Worksheets("Sheet3").Cells(1, 2).Value = count
If Finished = True Then
    Exit For
End If
    MsgBox "Next."
    If Flip_x_coins = stack Then
        GoTo Reset
    End If
Next Flip_x_coins

End Sub

提前致谢。

问候,伊恩

0 个答案:

没有答案