Do While x2 <> Abs(x1) - Abs(f1 / f2)
f1 = (4 * x1) - (16 / (x1 ^ 2))
f2 = 4 + (32 / (x1 ^ 3))
x2 = (x1) - (f1 / f2)
' Output to Screen
Cells(counter, 1) = x1
Cells(counter, 3) = f1
Cells(counter, 4) = f2
counter = counter + 1
Loop
上述循环变得无限。我怎么摆脱它?那里的错误是什么?
答案 0 :(得分:0)
更好的结构可能是让您的循环条件与目标的差异。此外,我放置了一些错误处理,以避免麻烦的条件。
Do While difference > 0.001
f1 = (4 * x1) - (16 / (x1 ^ 2))
f2 = 4 + (32 / (x1 ^ 3))
x2 = (x1) - (f1 / f2)
' Output to Screen
Cells(counter, 1) = x1
Cells(counter, 3) = f1
Cells(counter, 4) = f2
counter = counter + 1
'Avoid runaway condition
If counter > 1000 Then
MsgBox "WARNING!" & Chr(10) & "1000 cycles exceeded"
Exit Do
End If
'Divison by zero
If f2 = 0 Then
MsgBox "ERROR!" & Chr(10) & "Divion by zero"
Exit Do
End If
'calculate difference from target
difference = Abs(x2 - (Abs(x1) - Abs(f1 / f2)))
Loop
你也可以使用圆函数做这样的事情......
Do While round(x2 - (Abs(x1) - Abs(f1 / f2)),3) <> 0
或者这......
Do While round(x2,3) <> round(Abs(x1) - Abs(f1 / f2),3)
哪个最接近原始代码