First, a random thought:
The word "perfect" is one of such wonderfully rounded curves that seem to convey the meaning of itself - perfection.
I was trying to pursue perfection in this application that I created, and found it marred by errors instead.
First, I awkwardly forgot what an Int() function does. It rounds a number up to the nearest integer.
Then I got my variables mixed up:
number was the user-entered number; numRt was the square root of that number
I originally wrote:
If Int(number) = numRt Then
Return True
End If
What happened, of course, is that only 1 returned a true statement (only the square root of 1 could possibly equal 1).
This below would return the correct answer.
If Int(numRt) = numRt Then
Return True
End If
This is my final code
Dim num As String = Val(Me.txtNumber.Text)
If PerfectSquare(num) = True Then
Me.lblAnswer.Text = num & " is a perfect square."
Else
Me.lblAnswer.Text = num & " is not a perfect square."
End If
End Sub
Function PerfectSquare(ByVal number As Double) As Boolean
Dim numRt As Double = Math.Sqrt(number)
If Int(numRt) = numRt Then
Return True
End If
End Function
Private Sub txtNumber_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNumber.TextChanged
Me.lblAnswer.Text = ""
End Sub
No comments:
Post a Comment