VB中用递归求最大公约数的Function或sub过程,在窗体模块中调用,来对分数进行化简

2024-11-21 21:11:29
推荐回答(2个)
回答1:

Private Sub Command1_Click()
Dim m As Integer, n As Integer
m = Val(Text1.Text)
n = Val(Text2.Text)
If n = 0 Then Text3.Text = "除数不能为0!": Exit Sub
k = gcd(m, n)
Text3.Text = m / k
Text4.Text = n / k
End Sub

Function gcd(m As Integer, n As Integer) As Integer
If m Mod n = 0 Then gcd = n Else gcd = gcd(n, m Mod n)
End Function

回答2:

Public Function bb(A As Long, B As Long) As Long
Dim iA As Long, iB As Long
If A > B Then
iA = A
iB = B
Else
iA = B
iB = A
End If
bb = A Mod B
If bb = 0 Then
bb = B
Else
bb = bb(B, bb)
End If
End Function
'以上Function用递归求最大公约数,
'化简代码就自己写把。