PDA

View Full Version : function returns 0 for some reason



next
03-02-2008, 02:16 AM
I'm trying to recreate "SQRT" function, but having some issues:

Public Function MySqrt(i As Double) As Double
Dim x As Integer, result As Integer, temp As Double, n As Double

Do
x = x + 1
result = x * x
If (result >= i) Then
temp = i / x
n = (temp + x) / 2
Debug.Print n
Exit Do
End If
result = 0
Loop
End Function


Sub xxx()
Debug.Print MySqrt(24)
End Sub


My problem is very weird, "n" returns 4.9, but when i'm trying to use "MySqrt" in a sub or on a spreadsheet it returns "0". Why?

Thanks.

Bob Phillips
03-02-2008, 02:37 AM
Public Function MySqrt(i As Double) As Double
Dim x As Integer, result As Integer, temp As Double, n As Double

Do
x = x + 1
result = x * x
If (result >= i) Then
temp = i / x
n = (temp + x) / 2
Debug.Print n
Exit Do
End If
result = 0
Loop
MySqrt = n
End Function

Bob Phillips
03-02-2008, 02:39 AM
But this is a bit simpler



Public Function MySqrt(i As Double) As Double

MySqrt = Sqr(i)
End Function

next
03-02-2008, 10:35 AM
LOL, i thought about that cheat too.
THanks!