① 用VB語言編寫程序,求兩個正整數的最小公倍數
Private Sub Command1_Click()
Dim i As Long, j As Long, k As Long
Dim A As Long, B As Long
A = Val(InputBox("請輸入第一個正整數", "輸入"))
B = Val(InputBox("請輸入第二個正整數", "輸入"))
i = A
j = B
Do '求得A與B的最大公約數
DoEvents
If i > j Then
k = i
i = j
j = k
ElseIf i = j Then
Exit Do
End If
j = j - i
Loop
MsgBox "最小公倍數是" & A * B / i, , "輸出"
End Sub
'以下是加強版
Private Sub Command1_Click()
Dim i As Long, j As Long, k As Long
Dim A() As Double, B As Double, C As Double, D As Double, E As Double
Dim STA As String, STB As String
MsgBox "如果數據有效位超過15位,則有可能因位數過多造成計算結果的不準確,請注意輸入的數據。", , "提示"
STA = InputBox("請輸入正整數個數", "輸入")
STA = Trim(STA)
j = Len(STA)
STB = ""
For i = 1 To j
If Asc(Mid(STA, i, 1)) <> 32 Then STB = STB & Mid(STA, i, 1)
Next
STB = Left(STB, 323)
B = Val(STB)
If B < 2 Then
MsgBox "個數輸入不正確,退出", , "錯誤"
Exit Sub
ElseIf B > 2 ^ 31 - 2 Then
MsgBox "個數輸入不正確,退出", , "錯誤"
Exit Sub
Else
B = Int(B)
End If
ReDim A(1 To B)
For i = 1 To B
STA = InputBox("請輸入第" & i & "個正整數", "輸入")
STA = Trim(STA)
j = Len(STA)
STB = ""
For k = 1 To j
If Asc(Mid(STA, k, 1)) <> 32 Then STB = STB & Mid(STA, k, 1)
Next
STB = Left(STB, 323)
A(i) = Val(STB)
If A(i) < 1 Then
MsgBox "第" & i & "個正整數輸入不正確,退出", , "錯誤"
Exit Sub
Else
A(i) = Int(A(i))
End If
Next
For i = 1 To B - 1
C = A(i)
D = A(i + 1)
Do
DoEvents
If C > D Then
E = C
C = D
D = E
ElseIf C = D Then
Exit Do
End If
D = D - C
Loop
A(i + 1) = A(i) * A(i + 1) / C
Next
MsgBox "最小公倍數是" & A(B), , "輸出"
End Sub
② 用VB編程:求兩個整數的最小公倍數。
沒太多的時間修改,給你個例子:
方法簡述:最小公倍數等於兩個正整數相乘再除以兩個正整數的最大公約數(即a*b/g)。說明求兩個正整數最大公約數,自己查找。
vb程序代碼如下:
Private Sub Command1_Click()
Dim m As Integer, n As Integer
Dim g As Integer
dim t1 as integer,t2 as integer
m = InputBox("第一個數")
n = InputBox("第二個數")
t1=m 't1,t2是臨時變數
t2=n
g = IIf(m < n, m, n)
Do While g > 1
If m Mod g = 0 And n Mod g = 0 Then Exit Do
g = g - 1
Loop
Print m & "與" & n & "的最小公倍數為:" & (t1*t2)/g
End Sub