• 主页

Xn=累加和/2的递归算法问题,小分送上

shubo2000 2008-01-04 11:39:58

Debug.Print MatchP01(100, 3)
'正常结果应该是
'(100,1) =>100
'(100,2) =>50
'(100,3) =>75
'(100,4) =>112.5

End Sub
'P2801
'特别计算 Xn = (X1+...Xn-1)/2

Function MatchP01(MX1, Mn)
'Dim M1
M1 = 0
If Mn = 1 Then
M1 = M1 + MX1
MatchP01 = M1
Else
M1 = M1 + MatchP01(MX1, Mn - 1)
MatchP01 = M1 / 2
End If
End Function
...全文
75 点赞 收藏 8

8 条回复

shubo2000 2008-01-04

X1 = 100
X2 = (X1)/2 = 50
X3 = (X1+X2)/2 = 75
X4 = (X1+X2+X3)/2 = 112.5
...
Xn = (X1+...Xn-1)/2

Debug.Print MatchP01(100, 3)
End Sub

Function MatchP01(MX1, Mn)
'Dim M1
M1 = 0
If Mn = 1 Then
M1 = M1 + MX1
MatchP01 = M1
Else
M1 = M1 + MatchP01(MX1, Mn - 1)
MatchP01 = M1 / 2
End If
End Function

XN=((3/2)^(N-2))/2*X1
N>=2

X2=1/2*X1

XN=((3/2)^(N-2))/2*X1

x[n]=3 * x[n-1]/2 = {(3/2)^(n-2)}* x[2] (n>=3)

x[n] = (X1+...Xn-1)/2
= (X1+...Xn-2)/2 + x[n-1]/2
= X[n-1] + x[n-1]/2
= (3/2) * x[n-1]

'1个标签Label1,1个命令按钮command1
Option Explicit

Dim M As Double
Dim Mn As Long
Dim S As Double
Dim X() As Double

Private Sub Command1_Click()

Label1.Caption = MatchP01(M, 10)
End Sub

Dim i As Long
M = 100: Mn = 10 '初值
ReDim X(Mn)
For i = 1 To Mn
X(i) = 0
Next
End Sub

Function MatchP01(M1 As Double, N As Long) As Double
Dim i As Long
S = M1
X(1) = S
Debug.Print ("X(1)=" & X(1)) & " S=" & S
For i = 2 To N
X(i) = X(i) + X(i - 1) / 2
S = S + X(i)
Debug.Print ("X(" & i & ")=" & X(i)) & " S=" & S
Next
MatchP01 = S
End Function

shubo2000 2008-01-04

M1 = M1 + MatchP01(MX1, Mn - 1)

For i = Mn - 1 To 1 Step -1
M1 = M1 + MatchP011(MX1, i)
Next

VB基础类

7451

VB 基础类