2012-10-11 77 views
2

我試圖在Visual Basic中打印一個菱形。我的代碼的上半部分工作完美,但由於某種原因,我無法讓下半部分以類似的方式工作。在下半部分,在o(用於製作鑽石)之後打印出空格,而o的數量減少會將程序發送到無限循環?誰能幫忙?Visual Basic循環永不結束

下半部分可能是完全錯誤的,我還在上

在這裏工作是代碼:

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

請在發佈時仔細考慮縮進代碼 - 這種方式很難閱讀。 – Oded

回答

3

的問題是,你使用row爲您的出行計數器爲while循環,也作爲for循環的循環索引。上半場工作完全是偶然的。 row下半年永遠不會達到40,因爲它不斷被for循環劫持。

嘗試For i = 20 to spaces等等。

+0

謝謝,這使得它完美的工作。 – user1739123