-2

我正在尝试用 VB 创建帕斯卡的三角形。

这是我的代码(它使用格雷的理论):

Dim input As Integer = Val(TextBox1.Text)
Dim rownumber As Integer = 0
Dim columnumber As Integer = 1
Dim x As Integer = 1

Do Until rownumber = input
  Do Until rownumber = columnumber
    Label2.Text = 1
    If rownumber = 0 Then
      x = 1
      Label2.Text = x & " "
    Else
      x = x * ((Math.Abs(rownumber - columnumber)) / (columnumber))
      columnumber = columnumber + 1
      Label2.Text = Label2.Text & " " & x & " "
    End If
  Loop
  columnumber = 1
  rownumber = rownumber + 1
  Label2.Text = x & vbNewLine
Loop

另一个想法,这里我使用阶乘(通过函数),然后增加行和列的值。这是输出:

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

和代码:

Public Class Form1

Function factorial(ByVal n As Long)
  If (n <= 0) Then
    factorial = 1
  Else
    factorial = n * factorial(n - 1)
  End If
End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Label2.Text = Nothing
  Dim input As Integer = Val(TextBox1.Text)

  Dim n As Integer
  Dim r As Integer
  Dim c As Integer
  Dim rnum, cnum As Integer

  For rnum = 0 To input Step +1
    For cnum = 1 To (rnum + 1) Step +1
      c = factorial(cnum) / (factorial(rnum) * factorial(cnum - rnum))
      Label2.Text = Label2.Text & " " & c & " "
    Next
    Label2.Text = Label2.Text & vbCrLf
  Next
End Sub

结束类

4

1 回答 1

0

这条线

Label2.Text = x & vbNewLine

将 label2 重置为默认 x 并丢失您所做的所有更改。

另一个问题在这里:

If rownumber = 0 Then
  x = 1
  Label2.Text = x & " "
Else
  x = x * ((Math.Abs(rownumber - columnumber)) / (columnumber))
  columnumber = columnumber + 1
  Label2.Text = Label2.Text & " " & x & " "
End If

其中 x 仅在第一行中只有 1,但应该是第一列中的一个,以使算法有效。

于 2012-11-14T14:11:11.077 回答