我正在学习VB.NET 2008.我遇到过一种情况
我想在VB.NET 2008中使用Windows工具为前50个术语构建一个递归程序,如数字因子或斐波纳契系列。例如,在文本框中键入数字,单击按钮,数字的阶乘的输出将显示在标签上。内部代码应该以递归方式实现,而不是仅使用简单循环。
我找不到合适的方法来解决这个问题。
请帮帮我。
非常感谢。
答案 0 :(得分:0)
你有没有这样尝试过?
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As Integer
Dim Fac As Integer
x = TextBox1.Text
Fac = 1
For i = x To 1 Step -1
Fac = Fac * i
Next i
Label1.Text = Fac
End Sub
End Class
希望有助于
重新编辑以获得更好的效果:
Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)Handles Button1.Click
Try
Dim x As Long = (CLng(TextBox1.Text)))
Dim Fac As Long
Fac = 1
For i = x To 1 Step -1
Fac = Fac * i
Next i
Label1.Text = "Factorial Number: " & Fac
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
答案 1 :(得分:0)
您可以使用自我调用的递归函数。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = Factorial(CLng(TextBox1.Text))
End Sub
Function Factorial(ByVal number As Long) As Long
If number <= 1 Then
Return (1)
Else
Return number * Factorial(number - 1)
End If
End Function