源码如下: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次?
望指教。

解决方案 »

  1.   

    这是因为你用了递归来调用,n=3时递归调用n=2,然后调用n=1。所以函数会等到递归调用完成再返回到call语句下一行执行。基本上可以这样来理解,只是为了说明函数执行过程,所以这样写了,直接把它理解成嵌套的调用就好了
    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
      

  2.   

    单步执行看看
    递归这东西很难说的 说说你想要的结果吧
    Call func(n - 1) 形参会变 但实参没变还是3
      

  3.   

    Private Sub Command1_Click()
        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
      

  4.   

    递归的东西,进了函数,但之前的变量值在那个状态时还存在的,等到把所有的函数都执行完了,再回过头来执行那个FOR循环里的,
      

  5.   

    递归,你断点一步一步debug进去就明白了