
Dim N As Integer, e As Single, I As Integer, J As Integer, Jc As Double
N = Int(Val(InputBox("计算的睁备型项数N=", "输入", 5)))
Jc = 1
e = 1
For I = 1 To N
Jc = Jc * I
e = e + 1 / Jc
Next
Print "e=1+1/1!+1/2!+……+1/" N "! 滚搭= " e
End Sub
已经悉猜运行过,有什么问题请留言。
vb提供了指数函数:exp(x),就是用来计算e的x次方的。Private Sub Form_Click()
Dim x As Integer, a As Double
x = Val(InputBox("请输入X的值"))
a=exp(x)
Print "e^x =" &a
End Sub
答案补充:
错误在于对Loop While x ^ n / jc(n) <0.000001的理解,while是当……的时候继续循环,所以你的循环执行了一次,,这时候,因为新增卜中值大于允许逗山误差而提前结束了循环。在第一次循环里,因为n=1,阶乘结果也是1,导致整数结果。
修改:将循环条件的逻辑运算符倒过来,或者将while换成until。
另外,这样的计算仍存在缺陷,就是溢出!当n=13的时候,n!就会溢出。导致出错,所以,在循环条件里再加一个关于n的。
综合以上,代码可以写为:
Private Sub Form_Click()
Dim x As Integer, a As Double
x = Val(InputBox("请输入X的值"))
a = 1
Do
n = n + 1
新值 = x ^ n / jc(n)
a = a + 新值
Loop While 新值 >0.000001 And n <11
Print "e^x =" &a
End Sub
Function jc(n)
Dim i As Integer, f As Long
f = 1
For i = 1 To n
f = f * i
Next i
jc = f
End Function
代码如下:form上面前顷粗有一个慧镇名称乎顷为command1的按钮
Private Sub Command1_Click()
Dim i As Integer
Dim e As Double
Dim current As Double, last As Double
i = 1
e = 2
current = 1
Do
i = i + 1
last = current
current = 1 / factorial(i)
e = e + current
Loop While last - current >10 ^ -4
MsgBox e
End Sub
Function factorial(ByVal n As Integer) As Long
If n = 0 Then
factorial = 1
Else
factorial = n * factorial(n - 1)
End If
End Function
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)