I'm just a beginner in VB and I made a program which says if a number is a perfect square or not. When I enter a negative number I get an error. How can I fix this problem?
Thanks.
Printable View
I'm just a beginner in VB and I made a program which says if a number is a perfect square or not. When I enter a negative number I get an error. How can I fix this problem?
Thanks.
Don't allow the user to enter negative numbers. Check the number before you calculate whether it is negative, if negative notify the user saying "Negative number is not allowed. Enter the positive number". Likevb Code:
Option Explicit Sub main() Dim I As Integer I = InputBox("Enter the number:") If I < 0 Then Call MsgBox("The number you entered is negative. Please enter the positive numbers.", vbExclamation, App.Title) Else '... Your Calculations End If End Sub
cssriraman is correct!
to avoid errors,,avoid values that made the errors!! FILTER THEM!!
To further avoid errors, be sure the value entered is actually a number. This may look slightly more complicated, but it really isn't.
vb Code:
Option Explicit Private Sub Command1_Click() If Not IsNumeric(Text1.Text) Then 'makes sure the entered number is a number MsgBox "Please enter a numeric value." Else 'if it is, continue If CInt(Text1.Text) < 0 Then 'makes sure the entered number is non-negative MsgBox "Please enter a positive number." Else 'if it's a valid number, continue 'your calculations here End If End If End Sub
Oh thanks a lot guys, i remember doing this before. Must of got lost in the back of my head :S
Thanks :)
No problem.
Oh, and welcome to the forums!
:wave:
Thanks :)
Couldn't the Abs() function be used in the calculation?
Yes, but there is no such thing as a negative perfect square.Quote:
Originally Posted by sneakers
I have been thinking about that since I posted that reply. A negative number requires a positive multiplied by a negative and a square number is a number multiplied by itself. I wasn't sure of the "laws of math" concerning this but logic alone says you can't have a true negative square number with a square root etc.
However, the Abs() function could be used in a lost focus event to be sure the numbers are positive. This is just an easy way to filter out the negatives and software dealing with square roots has no need for a hyphen.