1. ## Square Root

This is my first code ive submitted so it wont be that good.

VB Code:
`Public num As Integer Public Function SquareRoot(TextBox As String)On Error Resume Nextnum = 1Donum = num + 1If num * num = TextBox Then Exit DoLoopMsgBox numEnd Function`

To use, put
VB Code:
`SquareRoot(25) 'change number`

2. ## Re: Square Root

Fine job, but I would point out one thing.

The Error Trap code will always execute unless you add an Exit Sub right before the Error Trap label.

3. ## Re: Square Root

Originally Posted by Hack
Fine job, but I would point out one thing.

The Error Trap code will always execute unless you add an Exit Sub right before the Error Trap label.
Actually it will not since he use a (yuck) GoTo statement that returns it back to the top where he checks if num * num <> the number to take the square root of. The error trap is in the Else clause and unless an error actually occurs it will never reach that part.

BTW, why not use the built in Sqr() function?

4. ## Re: Square Root

Actually it will not since he use a (yuck) GoTo statement that returns it back to the top where he checks if num * num <> the number to take the square root of. The error trap is in the Else clause and unless an error actually occurs it will never reach that part.
That was my kind of round about way of inferring the Goto be replaced with an Exit Sub.

5. ## Re: Square Root

It wouldn't work with an exit sub instead of the goto at that position. However a regular Do While loop would be so much cleaner then using an If together with a goto.

Also there are other logical errors with the code since it can only determent the square root of a number in which the square root itself is an integer... like 2, 4, 9, 16, 25, 36 and so on. Trying it with a number like 10 or 7 or something will eventually raise an overflow error.

6. ## Re: Square Root

Ah, i didnt think about Do loop, ive updated it.

7. ## Re: Square Root

But what if I wanted to know the square root of 26?

8. ## Re: Square Root

I dunno, im trying to fix it somehow

9. ## Re: Square Root

But as I already mentioned, VB already has a built in function for this. It's called Sqr().
VB Code:
`MsgBox Sqr(25)`

10. ## Re: Square Root

Yes, but im trying to build my own

11. ## Re: Square Root

Originally Posted by SlicedCheese
Yes, but im trying to build my own
Then learn a square root algo:

13. ## Re: Square Root

Originally Posted by SlicedCheese
This is my first code ive submitted so it wont be that good.

VB Code:
`Public num As Integer Public Function SquareRoot(TextBox As String)On Error Resume Nextnum = 1Donum = num + 1If num * num = TextBox Then Exit DoLoopMsgBox numEnd Function`

Since this post is two years old, I'll assume that SlicedCheese has either completed his homework or failed. Some suggestions:
1. Your Function SquareRoot() will default to the Variant data type, since you failed to declare one. While this will work, it should be declared as a Double, so it can more efficiently return rational results, e.g., the square root of 27 = 5.19615242270663.
2. If you plan to use the function throughout your application, put it in a public module or make a math class with various math functions in it.
3. Making the variable num global is bad practice. Best practice is to declare (i.e., Dim) num local to (i.e., inside of) your function so that it lives and dies there each time the function is called.
4. The variable num should also be declared a Double, instead of an Integer, as the latter will return "0" for rational results.
5. Change the SquareRoot() parameter TextBox As String to a Variant so it can accept various input types.
6. The statement num * num will raise your input to the power of 2 (e.g., x^2), not calculate the square root. To calculate a square root in VB without using VB's Sqr() function, raise the number to the equivalent fractional power, e.g., x^(1/2). This is high school math.
7. If you want to loop through a set of numbers to calculate their square roots, do so in a separate procedure, and call SquareRoot() from there.
8. Finally, you should conditionally trap your errors at the bottom of the function.

This example is clean, unambiguous, self documenting, and maintainable code. I've replaced the variable num with dBase. This example could be improved by fine tuning the conditional error check. Since this is a wasteful redundancy of VB's Sqr() function, a more useful exercise, left to the reader, would be to code a function that can calculate any root , e.g., cube root, 4th root, etc.:

VB Code:
`Private Sub cmdCalcSqrt_Click()    Dim dOutput As Double        lblResult = ""    dOutput = Sqrt(txtInput)        If dOutput > 0 Then        lblResult.Caption = "{" & dOutput & ", -" & dOutput & "}"    Else        Dim sErrPrompt As String   'Dim sErrPrompt  <-- Corrected at Errata 2        sErrPrompt = "Error: Could not calculate root. " & vbCrLf & _                     "Check your input."        ShowErrorMsg (sErrPrompt)    End IfEnd Sub Private Function Sqrt(vRadicand As Variant) As Double    On Error GoTo ErrHandler:    Dim dBase As Double        dBase = CDbl(vRadicand)    Sqrt = dBase ^ (1 / 2)Exit Function   '<-- Corrected at Errata 3ErrHandler:    If Err.Number > 0 Then        Dim sErrPrompt As String   'Dim sErr As String <-- Corrected at Errata 1        sErrPrompt = "Error No. " & Err.Number & " @ Function SquareRoot." & vbCrLf & _                     "Description: " & Err.Description        ShowErrorMsg (sErrPrompt)    End IfEnd Function Private Sub ShowErrorMsg(sErrPrompt As String)    MsgBox sErrPrompt, vbExclamation, "Error!"End Sub`

14. ## Re: Square Root

Errata:
OOPS! Turning Option Explicit on revealed a Variable not defined error on line 27, caused by an incomplete variable name on line 26. Lines 24 - 30 debugged,

VB Code:
`ErrHandler:    If Err.Number > 0 Then        Dim sErrPrompt As String        sErrPrompt = "Error No. " & Err.Number & " @ Function SquareRoot." & vbCrLf & _                     "Description: " & Err.Description 'Line 27 wrapped        ShowErrorMsg (sErrPrompt)    End If`

15. ## Re: Square Root

Errata 2: Declared data type for sErrPrompt on line 10,

VB Code:
`Dim sErrPrompt As String`

16. ## Re: Square Root

Errata 3: To improve efficiency, inserted Exit Function at line 23. This avoids processing the statements after the ErrHandler: label each time the function is called, even when no error has occurred.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Featured