VB 求一个数各位数字的阶乘之和

2025-02-23 23:40:11
推荐回答(2个)
回答1:

Private Sub Command1_Click()
Dim i As Integer, n'定义的类型去掉就没问题了
Dim a As Integer, s As Long
n = Val(Text1.Text)
For i = 1 To Len(n)
a = Mid(n, i, 1)
s = s + fact(a)
Next i
Text2.Text = CStr(s)
End Sub
Private Function fact(ByVal x As Integer) As Long
fact = 1
Do Until x = 1
fact = fact * x
x = x - 1
Loop
End Function

回答2:

Private Sub Command1_Click()
Dim n, n1 As Integer, product As Long, remainder As Single
n = Val(InputBox("Input the number:"))
n1 = n
remainder = 10 * n Mod 10
If remainder > 0 Then
Print "Error"
Else
If n > 0 Then
If n = 1 Then
Print "The factorial of"; n1; "is: 1"
Else
product = n * (n - 1)
While n - 1 > 1
n = n - 1
product = product * (n - 1)
Wend
Print "The factorial of"; n1; "is:"; product
End If
Else
If n = 0 Then
Print "The factorial of"; n1; "is: 1"
Else
Print "Error"
End If
End If
End If
End Sub

Private Sub Command2_Click()
Dim n, n1 As Integer, product As Long, remainder As Single
n = Val(Text1. Text)
n1 = n
remainder = 10 * n Mod 10
If remainder > 0 Then
Text2. Text = "Error"
Else
If n > 0 Then
If n = 1 Then
Text2. Text = "The factorial of"; n1; "is: 1"
Else
product = n * (n - 1)
While n - 1 > 1
n = n - 1
product = product * (n - 1)
Wend
Text2. Text = "The factorial of"; Str(n1); "is:"; Str(product)
End If
Else
If n = 0 Then
Text2. Text "The factorial of"; Str(n1); "is: 1"
Else
Text2. Text = "Error"
End If
End If
End If
End Sub