用VB计算e=1+1⼀1!+1⼀2!+1⼀3!+···+1⼀n!+····并要求误差小于0·000001

用for语句该怎么编?
2024-12-04 11:42:30
推荐回答(5个)
回答1:

误差小于0·000001:
要么你直接把e的原值写进程序中,每次计算后比较误差。
要么你比较每次计算前后e的差值,当差值小于一定的时候,就算误差小于误差小于0·000001 。
个人看法:看公式,当计算到第n项1/n!时,从这一项开始,后面所有的值加起来是小于e* 1/n!的,e≤e'+e*1/n!(e'是当前计算的e值),变换一下得到:误差e-e'≤e‘*1/(n!-1)。
计算n!的时候别用循环了,你用一个变量把n!保存起来,计算(n+1)!的时候直接乘个(n+1)。计算1/n!用除法也一样。
计算完e'后,再计算下误差e‘*1/(n!-1)的大小,如果小于0·000001就退出循环。
以上仅供参考,不保证是否正确……

回答2:

for(i=1;i{
for(j=1;j<=i;j++)
e=e+1/j;
}原理。嵌套循环。让e的初始值=1;

回答3:

计算了1000000次
Private Sub Command1_Click()
Dim sum As Double
Dim preSum As Double
Dim a As Double
Dim i As Long
sum = 0
preSum = 0
a = 1
For i = 1 To 10000000
a = 1 / i
sum = sum + a
Debug.Print sum - preSum
If sum - preSum <= 0.000001 Then

Exit For
End If
preSum = sum
Next
MsgBox sum & "累加次数:" & i
End Sub

回答4:

Private Sub Command1_Click()
Dim n%, k%, Sum!
n = InputBox("请输入数列的项数:")
For k = 1 To n
Sum = Sum + 1 / JC(k)
Next
Print Format(Sum, "#0.000000")
End Sub
Private Function JC(x As Integer)
If x = 1 Then
JC = 1
Else
JC = x * JC(x - 1)
End If
End Function

回答5:

Sub cc()
Dim n%, E As Double
n = 156: E = 2
For I = 2 To n
v = 1
For j = 1 To I
v = v * j
Next
E = E + 1 / v
Next
MsgBox E
End Sub