源码如下:Private Sub Command1_Click()
Call func(3)
End SubFunction func(ByVal n As Integer)
Dim i As Integer
If n <> 0 Then
Call func(n - 1)
For i = 0 To n
Print n
Next
Print n
End If
End Function
执行后结果:
1
1
1
2
2
2
2
3
3
3
3
3 这样我就弄不明白了,为什么会有这个结果出来呢?
Call func(n - 1)后,n将会等于0,这样就跳出了func这个函数。
为什么还会返回去执行for循环体,而且是n=1、n=2、n=3这样执行3次?
望指教。
Call func(3)
End SubFunction func(ByVal n As Integer)
Dim i As Integer
If n <> 0 Then
Call func(n - 1)
For i = 0 To n
Print n
Next
Print n
End If
End Function
执行后结果:
1
1
1
2
2
2
2
3
3
3
3
3 这样我就弄不明白了,为什么会有这个结果出来呢?
Call func(n - 1)后,n将会等于0,这样就跳出了func这个函数。
为什么还会返回去执行for循环体,而且是n=1、n=2、n=3这样执行3次?
望指教。
Function func(ByVal n As Integer)
Dim i As Integer
If n <> 0 Then
'n=2, 调用函数里面是call func(n-1)
Function func(ByVal n As Integer)
Dim i As Integer
If n <> 0 Then
'n=1,调用函数里面是call func(n-1)
Function func(ByVal n As Integer)
Dim i As Integer
If n <> 0 Then
'Call func(n - 1)
Function func(ByVal n As Integer)
Dim i As Integer
If n <> 0 Then
Call func(n - 1)
For i = 0 To n
Debug.Print n
Next
Debug.Print n
End If
End Function
'直接跳出,因为此时函数形参为0。
For i = 0 To n
Debug.Print n
Next
Debug.Print n
End If
End Function
'n=1 end
For i = 0 To n
Debug.Print n
Next
Debug.Print n
End If
End Function
'n=2结束
For i = 0 To n
Debug.Print n
Next
Debug.Print n
End If
End Function
递归这东西很难说的 说说你想要的结果吧
Call func(n - 1) 形参会变 但实参没变还是3
Call func(3)
End Sub
Function func(ByVal n As Integer)
Dim i As Integer
If n <> 0 Then
For i = 0 To n
Print n
Next
Print n
Call func(n - 1)'移到这里递归
End If
End Function