Dear Sir/Madam,
I have one assignment , which need me to
write a program to calculate the factorial of an integer,
then press the button that would display the result in a label.3
& the program should warn the user if the
iinput is not a number.
I have tried my best to write ,but It show me
something wrong,
What I write is as following, Please help me to show what is going wrong !
Thanks !
Tin
Dim N As Integer = CInt(TextBox1.Text)
Dim sum As Integer
Dim Factorial As Integer
Try
N = Integer.Parse(TextBox1.Text)
sum = N * Factorial(N - 1)
Label3.Text = CStr(sum)
Catch ex As FormatException
MessageBox.Show("Number is not an integer. Please enter an Integer ")
End Try
End Sub
Function Factorial(ByVal N As Integer) As Integer
If N = 0 Then
Return 1
Else
Return N * Factoria((N - 1) - 1)
End If
End Function
Hi, a couple of things might help.
The Try...Catch block is C++ programming and is not part of VB6
You need to make sure that the input number is 171 or less or you will get an overflow error as the factorial of 172 is too large to store in a Double.
You have declared an integer with the same name as the function.
The following works
-
Private Sub cmdFactorial_Click()
-
Dim dblN As Double
-
Dim dblFactorial As Double
-
-
If IsNumeric(TextBox1.Text) _
-
And Len(TextBox1.Text) < 4 Then
-
dblN = CLng(TextBox1.Text)
-
If dblN > 170 Then
-
MsgBox "Please enter a numeric value between 1 and 170"
-
TextBox1.Text = ""
-
TextBox1.SetFocus
-
Exit Sub
-
End If
-
Else
-
MsgBox "Please enter a numeric value between 1 and 170"
-
TextBox1.Text = ""
-
TextBox1.SetFocus
-
Exit Sub
-
End If
-
dblFactorial = Factorial(dblN)
-
TextBox1.Text = dblFactorial
-
End Sub
-
-
Private Function Factorial(dblNum As Double) As Double
-
If dblNum - 1 = 0 Then
-
Factorial = dblNum
-
Exit Function
-
End If
-
Factorial = dblNum * Factorial(dblNum - 1)
-
End Function
-