2012-11-07 43 views
-2

我已經創建了一個程序,將顯示X條記錄並重復:楊輝三角 - VB.NET

1 
2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5 
6 6 6 6 6 6 

現在,我想使楊輝三角

回答

1

也許像這樣:

Dim arr As Integer(,) = New Integer(7, 7) {} 
For i As Integer = 0 To 7 
    For k As Integer = 7 To i + 1 Step -1 
     'print spaces 
     Console.Write(" ") 
    Next 

    For j As Integer = 0 To i - 1 
     If j = 0 OrElse i = j Then 
      arr(i, j) = 1 
     Else 
      arr(i, j) = arr(i - 1, j) + arr(i - 1, j - 1) 
     End If 
     Console.Write(arr(i, j) & " ") 
    Next 
    Console.WriteLine() 
Next 

控制檯輸出:

enter image description here

+0

當時的代碼C#代碼? :) – Neolisk

+0

好吧,我得到這個在控制檯應用程序中工作,但我想使它在用戶輸入行號的窗體樣式。我現在是自學VB,因此我試圖理解這個例子。你能提供一個小的解釋它如何工作?非常感謝 ! –

+0

我在上面添加了一些新代碼,如果你能看一看,我會更好地理解它。謝謝 –

0

另一種方法,只保留以往和當前迭代內存:

Dim oldList As New List(Of Integer)({0, 1}) 
For line = 1 To 7 
    Dim newList As New List(Of Integer) 
    For i = 1 To oldList.Count - 1 
    newList.Add(oldList(i - 1) + oldList(i)) 
    Next 
    Debug.Print(String.Join(" ", newList)) 
    oldList.Clear() 
    oldList.Add(0) 
    oldList.AddRange(newList) 
    oldList.Add(0) 
Next 
+0

嗯,我不知道這是如何創建Pascal的三角形... –

+0

@DavidSalib:試試吧 - 完美的爲我工作。 :) – Neolisk

+0

我該如何輸出這個標籤,以及如何使用戶輸入的行數變量? –

0

做,使用Windows窗體,你需要一個文本框,多行文本框和一個按鈕上設計界面

這裏是你需要最初生成它

Imports System.Numerics 'this allows you to use big integer 

Public Class pascal_triangle 


    Private Function factorial(ByVal k As Integer) As BigInteger 

'big integer allows your proram compute for inputs of more than 22 

     If k = 0 Or k = 1 Then 

      Return 1 

     Else 

      Return k * factorial(k - 1) 


     End If 

    End Function 



    Private Sub BtnGen_Click(sender As Object, e As EventArgs) Handles BtnGen.Click 
     Dim nCr As Double 

     Dim i, j, k As Integer 


     Dim output As String 

     output = "" 

     j = Val(TxtColumn.Text) 

     For k = 0 To j 

      For i = 0 To k 

       Dim fact, fact1, fact2 As BigInteger 



       fact = factorial(k) 

       fact1 = factorial(k - i) 

       fact2 = factorial(i) 

       nCr = fact/(fact1 * fact2) 

       TxtOutput.Text += Str(nCr) & output 





      Next 

      TxtOutput.Text += vbCrLf 

     Next 



    End Sub 


    Private Sub pascal_triangle_Load(sender As Object, e As EventArgs) Handles MyBase.Load 

    End Sub 
End Class