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

shubo2000 2008-01-04 11:39:58
特别计算 Xn = (X1+...Xn-1)/2

下面代码应该如何修改?我实在没办法了,谢谢高手。

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

下面是自己写的代码,没调试成功

Private Sub Form_Load()
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
回复
同意LS
这种问题 最好是能用数学的方法先简化它
根据LS的推论
X2=1/2*X1
当N>=3
XN=((3/2)^(N-2))/2*X1
回复
如果 Xn = (X1+...Xn-1)/2,那么这个数列很简单:从n>=3之后开始就是一个等比数列:
x[n]=3 * x[n-1]/2 = {(3/2)^(n-2)}* x[2] (n>=3)

证明如下,当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.5的等比数列
回复
东方之珠 2008-01-04
上面换成:Label1.Caption=MatchP01(M,Mn),才具有一般性
回复
东方之珠 2008-01-04
'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

Private Sub Form_Load()
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
回复
波导终结者 2008-01-04
接分。
用动态规划会快多了
回复
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基础类
创建于2007-09-28

7451

社区成员

VB 基础类
申请成为版主
社区公告
暂无公告