[整理后再开一贴]一个递归算法,错在哪里,请高手进来指点,谢谢!
r为已知整数,x为已知实数,求满足以下条件的函数值H(r,x)
当r=0,H(r,x)=1 ;
当r=1,H(r,x)=x ;
当r> 1,H(r,x)=2*x*H(r-1,x)-H(r-2,x)
这是一个递归计算,我这样写错在哪里,以前没接触过递归算法,请大家指点,谢谢。
Public Function H(r, x) As Double
Dim r1 As Long, r2 As Long
If r = 0 Then
H = 1
ElseIf r = 1 Then
H = x
Else
r1 = r - 1: r2 = r - 2
H = 2 * x * H(r1, x) - H(r2, x)
End If
End Function
[解决办法]
把Public Function H(r, x) As Double改为Public Function H(r as long, x as double) As Double
能使运算速度快一些!不过r仍不宜过大,要不可能堆栈溢出!
你的代码基本上是正确的
[解决办法]
帮你改进了下 你的程序用递归其实效率很低
Private Sub Command1_Click()
Static r As Long
r = r + 1
Print H(r + 25, 1.5), r
End Sub
Public Function H(r As Long, x As Double) As Double
Dim i As Long, j As Long, t1 As Double, t2 As Double, t2t As Double
i = 0
t1 = 0
t2 = 0
t2t = 0
Do While i <= r
If i = 0 Then
t2 = 1
ElseIf i = 1 Then
t1 = 1
t2 = x
Else
t2t = t2
t2 = 2 * x * t2 - t1
t1 = t2t
End If
i = i + 1
Loop
H = t2
End Function
[解决办法]
r1 = r - 1: r2 = r - 2
H = 2 * x * H(r1, x) - H(r2, x)
是不是有问题?
按照描述:当r> 1,H(r,x)=2*x*H(r-1,x)-H(r-2,x),觉得你应该直接写成 H = 2 * x * H(r-1, x) - H(r-2, x)。
[解决办法]
Public Function H(ByVal r As Long, ByVal x As Double) As Double
If r <= 1 Then H = x ^ r
If r > 1 Then H = 2 * x * H(r - 1, x) - H(r - 2, x)
End Function