一般程序都自帶平方根算法,比如Math.Sqrt
還可以用二分法求解平方根。
Imports System.Math
Public Class Form1
Function sqrt1(x As Double) As Double
Dim EPSINON, low, high, mid As Double
EPSINON = 0.0000000000001 '精度
low = 0.0
high = x
While ((high - low) > EPSINON)
mid = (low high) / 2
If mid * mid = x Then Exit While
If (mid * mid > x) Then
high = mid
Else
low = mid
End If
End While
Return mid
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim a, b1, b2 As String
a = CInt(TextBox1.Text)
b1 = CStr(Math.Sqrt(a))
b2 = CStr(sqrt1(a))
MsgBox(b1 vbCrLf b2)
End Sub
就是定義一個最小值0和最大值number,把一個數取一個中間值(0 number)/2,然後平方,如果平方大于該數值,就把中間值賦給最大值,否者就把中間值賦給最小值,一直循環,直到取到想要的精度為止
注意:
EPSINON = 0.0000000000001 '精度
通過調整精度,可以得到近似值。
因為二分法本質是一種逼近算法,通過不斷二分逼近,可以得到精确值。
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!