Visual Basic循环永远不会结束

时间:2012-10-11 18:43:15

标签: vb.net visual-studio-2010 visual-studio loops

我正在尝试在Visual Basic中打印钻石。我的代码的上半部分工作得很好,但由于某种原因,我不能让下半部分以类似的方式工作。在下半部分,在o(用于制作钻石)之后打印出空格,并且减少数量的o将程序发送到无限循环中?有人可以帮忙吗?

下半部分可能完全错误,我还在努力

以下是代码:

Option Explicit On
Imports System

Module diamond
    Sub Main()
        ' The o variable will make the "o" part of the diamond, the space variable will be for places without an "o". 
        Dim row, spaces, o as Integer  
        'Dim index as integer

        'For top half
        ' Count the row number.
        row = 1
        spaces = 9
        o = 1
        Do until row = 20
            ' Count of row increases every loop until half of diamond is done.
            row +=1
            ' Write 1 less space every line.
            For row = 1 to spaces
                console.write(" ")
            Next row
            spaces -=1
            'Write 2 more "o"'s every loop.
            For row = 1 to o 
                Console.write("o")
            Next row    
            o +=2
            Console.Writeline
        Loop
        'Top of the diamond is done

        'This is the bottom half, which will not work.
        row = 20

        Do until row = 40
            row +=1
            For row = 20 to spaces
                Console.write(" ")
            Next row
            spaces +=1
            'Write 2 less "o"'s every loop.
            For row = 20 to o 
                Console.write("o")
            Next row    
            o -=2
            Console.Writeline
        Loop
    End Sub
End Module 

1 个答案:

答案 0 :(得分:3)

问题是您使用row作为while循环的行计数器,并且还作为for循环的循环索引。上半场工作是偶然的。在下半场row永远不会达到40,因为它一直被for循环劫持。

请尝试使用For i = 20 to spaces等。