Public Function power(x As Integer, y As Integer) As Long
    Dim result As Long
    result = 1
    If y < 1 Then
        MsgBox "幂应该大于等于1"
        Exit Function
    Else
        If y = 1 Then
            result = x
        End If
        
            While y > 1
            result = power(x, y - 1) * x
            y = y - 1
            Wend
       
    
    End If
    power = result
End Function
可是得出的结果当幂一超过2就结果不对,大虾指正一下吧

解决方案 »

  1.   

    Public Function power(x As Integer, y As Integer) As Long
        Dim result As Long
        result = 1
        If y < 1 Then
            MsgBox "幂应该大于等于1"
            Exit Function
        Else
            If y = 1 Then
                result = x
            Else
                result = x ^ y
            End If
            
    '            While y > 1
    '            result = power(x, y - 1) * x
    '            y = y - 1
    '            Wend
           
        
        End If
        power = result
    End Function
      

  2.   

    因为你的递归方法错了.当y=1时,由于
           If y = 1 Then
                result = x
            End If
    使前面result的结果x的y-1次密,变成了x.
    正确的代码为
           if y > 1 then
              power=power(x,y-1)*x
           elseif y=1
              power=x
           end if
      

  3.   

    Private Function power(x As Integer, y As Integer) As Long
        Dim result As Long
        
        result = x
        
        If y < 1 Then
            MsgBox "幂应该大于等于1"
            Exit Function
        Else
            While y > 1
                y = y - 1
                result = power(x, y) * x
            Wend
        End If
        
        power = result
    End Function
      

  4.   

    vb提供了现成的:x^y ,有必要重写吗,当然练习递归另当别论
      

  5.   

    顺便说一句,用递归就没有必要用循环:Private Function power(x As Integer, y As Integer) As Long
            
        If y < 1 Then
            MsgBox "幂应该大于等于1"
            Exit Function
            
        ElseIf y = 1 Then
        
            power = x
            
        Else
        
            power = power(x, y - 1) * x
            
        End If
        
    End Function