2009年4月7日 星期二

N 階乘

image image

'n 階乘
Public Class Form1
    Dim i
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '一般迴路法
        Dim n = 5
        'Dim n = Val(InputBox("請輸入一個整數:"))
        Dim s = 1
        For i = n To 1 Step -1
            s = s * i
        Next
        MsgBox(n & "!=" & s)

        '遞迴法
        n = 6
        s = fact(n)
        MsgBox(n & "!=" & s)
    End Sub

    Function fact(ByVal n)
        If n = 1 Then
            fact = 1
        Else
            fact = n * fact(n - 1)
        End If
    End Function
End Class

沒有留言:

張貼留言