问题描述
我的列表代码有问题。 在我的代码中,函数 f(x) 一遍又一遍地重复,而我只需要 f(x1) 和 f(x2)。
这是细节
Function f(x)
f(x) = tan(x) - ((Cells(16,2).Value) * (Cells(8,6).Value)) / (2 * (Cells(4,2).Value) * (Cells(4,2).Value) * Cos(x) * Cos(x))
End Function
Sub solusiNumSudutElevasi()
Dim xm,ym As Double
Dim g,pi As Double
Dim v0,x1,x2,xS As Double
Dim slope,error,i As Double
error = 0.000001
g = Cells(16,2).Value
pi = Cells(15,2).Value
v0 = Cells(4,2).Value
xm = Cells(8,6).Value
ym = Cells(9,6).Value
'memasukkan x0,x1
x1 = Cells(13,6).Value / 180 * pi
x2 = Cells(14,6).Value / 180 * pi
'hitung slope
slope = (f(x1) - f(x2)) / (x1 - x2)
'hitung x2,setup counter iterasi
xS = x1 - (f(x1) / slope)
i = 0
'Bila f(theta) = 0 maka theta adalah akarnya
'Bila tidak,cari dengan metode Secant
If f(x1) = 0 Then
Cells(15,6).Value = x1
ElseIf f(x2) = 0 Then
Cells(15,6).Value = x2
ElseIf f(xS) = 0 Then
Cells(15,6).Value = xS
Else
do while (Abs((xS - x2) / xS) > error) And (f(xS) <> 0)
x1 = x2
x2 = xS
i = i + 1
slope = (f(x1) - f(x2)) / (x1 - x2)
xS = x1 - (f(x1)) / slope
Loop
Cells(15,6).Value = xS
End If
End Sub
解决方法
首先,将您的功能更改为
f = Tan(x) - ((Cells(16,2).Value) * (Cells(8,6).Value)) / (2 * (Cells(4,2).Value) * (Cells(4,2).Value) * Cos(x) * Cos(x))
您需要将返回值设置为等于不带参数的函数名。您现在拥有的方式可能是一遍又一遍地调用该函数。
接下来,像这样声明变量
Dim xm,ym As Double
与
相同Dim xm as Variant,ym As Double
你可能想
Dim xm as Double,ym As Double
不幸的是,您必须明确键入每个变量。没有捷径。