一个计算阶成的例子 funciton a (i as integer) if i = 1 a = 1 else a = i * a(i - 1) endif end function
传入一个小于1的数进去楼上的那个函数 会造成死循环的Public Function Factorial(ByVal N As Integer) As Double If N <= 1 Then Factorial= 1 Else Factorial= N * Factorial(N - 1) End If End FunctionPrivate Sub Command1_Click() Dim N As Integer N = 7 Debug.Print "Factorial(" & N & ")=" & Factorial(N) End Sub
你到底是问 C 还是问 VB 啊?
用递归函数数,要搞清递归口和递归体. 下面是一个求阶成的例子 unsigned long mul(int n) { unsigned long p; if(n>1) p=n*mul(n-1); /*递归体,调用计算n!*/ else p=1L; /*递归口*/ return(p); }
funciton a (i as integer)
if i = 1
a = 1
else
a = i * a(i - 1)
endif
end function
会造成死循环的Public Function Factorial(ByVal N As Integer) As Double
If N <= 1 Then
Factorial= 1
Else
Factorial= N * Factorial(N - 1)
End If
End FunctionPrivate Sub Command1_Click()
Dim N As Integer
N = 7
Debug.Print "Factorial(" & N & ")=" & Factorial(N)
End Sub
下面是一个求阶成的例子
unsigned long mul(int n)
{
unsigned long p;
if(n>1)
p=n*mul(n-1); /*递归体,调用计算n!*/
else
p=1L; /*递归口*/
return(p);
}