vb編程階乘
❶ 怎麼寫vb的階乘代碼
1、For語句蔽緩實現
Private Sub Command1_Click()
Dim s As Long, n As Integer, i As Integer
培並氏 n = Val(Text1.Text)
s = 1
For i = 1 To n
s = s * i
Next i
Label4.Caption = Str(s)
End Sub
2、Do While語句實現
Private Sub Command1_Click()
Dim s As Long, n As Integer, i As Integer
n = Val(Text1.Text)
s = 1
i = 1
配散 Do While i <= n
s = s * i
i = i + 1
Loop
Label4.Caption = Str(s)
End Sub
(1)vb編程階乘擴展閱讀:
1~10的階乘的結果如下:
1!=1
2!=2*1=2
3!=3*2*1=6
4!=4*3*2*1=24
5!=5*4*3*2*1=120
6!=6*5*4*3*2*1=720
7!=7*6*5*4*3*2*1=5040
8!=8*7*6*5*4*3*2*1=40320
9!=9*8*7*6*5*4*3*2*1=362880
10!=10*9*8*7*6*5*4*3*2*1=3628800
❷ VB階乘的演算法
求階乘的兩種演算法
方法一(計數循環)
使用For語句。
Function Factorial(n As Integer) As Long
On Error GoTo Hander
Dim i As Long
Factorial = 1
For i = n To 1 Step -1
Factorial = Factorial * i
Next i
Exit Function
Hander:
MsgBox "數值過大!", vbExclamation, "Error"
Resume Next
End Function
方法二(遞歸)
簡單地說,遞歸就是一個過程調用過程本身。
思路為:n! = n * (n-1)!
Function Factorial(n As Integer) As Long
On Error Goto Hander
If n > 0 Then
Factorial = n * Factorial(n - 1)
Else
Factorial = 1
End If
Exit Sub
Hander:
Msgbox "數值過大!",vbExclamation,"Error"
Resume Next
End Function
例如,當 n=5 時,求 Factorial(5) 的值變為 5 * Factorial(4)。而 Factorial(4) 又可變為 4 * Factorial(3) ......,Factorial(2)又可變為 2 * Factorial(1),這時 Factorial(1) = 1 已知,遞歸調用停止,其執行結果為 5 * 4 * 3 * 2 * 1,即 5! 。
過程中還是用了錯誤陷阱(On Error...),以防數值過大發生溢出錯誤。
❸ VB編程,求階乘的過程
VB求階乘需要Function 過程來實現。
Function 語句,聲明 Function 過程的名稱,參數以及構成其主體的代碼空局。
以下是求輸入數的階乘代碼:
OptionExplicit
DimSumAsDouble
DimNAsInteger
DimiAsInteger
PrivateFunctionfact(NAsInteger)AsDouble
fact=1
則虧凱DoWhileN>0
fact=fact*N
N=N-1
孫喚Loop
EndFunction
PrivateSubCommand1_Click()
N=Val(Text1.Text)
Sum=fact(N)
Text2=Sum
EndSub
PrivateSubForm_Load()
Text1="":Text2=""
EndSub
❹ VB 計算階乘
PrivateSub乎畝拿Form_Click()
DimpAsLong,nAsInteger,iAsInteger
p=1
n=Val(InputBox("input耐老n",,5))
Fori=1To歲搭n
p=p*i
Next
Printp
EndSub
❺ vb編程求n的階乘
DimsAsDouble,nAsInteger
n=Val(InputBox("請輸入n值,不要罩茄太大哦,否則出錯"))
s=1
DoWhilen>襪拆1
s=s*n
n=物好察n-1
Loop
MsgBox"這個數的階乘為"&s
❻ vb如何輸入階乘
'給你一禪察個轎襲喊自定義函數
Function cjhs(a As Long) As Long
cjhs = 1
For i = 1 To a
cjhs = cjhs * i
Next
End Function
Private Sub Command1_Click()
'引用方法
't等閉野於3的階乘
t = cjhs(3)
End Sub