求用VB做最大公约数和最小公倍数
要求可以用text控件任意输入数 并且输出最大公约数和最小公倍数
追问:你的代码有误先 做测试再发我 exit() 这个我不懂输出什么值
要求可以用text控件任意输入数 并且输出最大公约数和最小公倍数
追问:你的代码有误先 做测试再发我 exit() 这个我不懂输出什么值
答案:Private Function MinGongBeiShu(num() As Variant)
Dim i, k, max As Integer
Dim flag As Boolean
max = num(0)
For i = 0 To UBound(num) '求最大数
If max < num(i) Then
max = num(i)
End If
Next ik = max '从最大数开始
Do While True
flag = True
For i = 0 To UBound(num)
If k Mod num(i) <> 0 Then
flag = False
Exit For
End If
Next i
If flag = True Then
Exit Do '跳出循环
Else
k = k + 1
End If
Loop
MinGongBeiShu = k
End FunctionPrivate Function MaxGongYueShu(num() As Variant)
Dim i, j, k, min, max As Integer
Dim flag As Booleanmin = num(0)
For i = 0 To UBound(num) '求最小数
If min > num(i) Then
min = num(i)
End If
Next imax = num(0)
For i = 0 To UBound(num) '求最大数
If max < num(i) Then
max = num(i)
End If
Next ik = num(0) '从第一个数开始
j = 1
Do While True
flag = True
For i = 0 To UBound(num)
If num(i) Mod k <> 0 Then
flag = False
Exit For
End If
Next i
If flag = True Then '找到了最大公约数或者j大于数组上界就跳出循环
Exit Do '跳出循环
Else
k = num(j) '后移
j = j + 1
If j > UBound(num) Then
If flag = False Then
k = 1 '如果整个数组遍历后没找到最大公约数则把k置1
End If
Exit Do
End If
End If
Loop
MaxGongYueShu = k
End FunctionPrivate Sub Command1_Click()
Dim str() As String
Dim i As Integer
Dim num() As Variantstr = Split(Text1.Text, " ")
ReDim Preserve num(UBound(str))
For i = 0 To UBound(str)
num(i) = Val(str(i))
Next iText2.Text = MinGongBeiShu(num)
分别建立text1、text2(输入两整数)、text3(最大公因数)、text4(最小公倍数)和command1(计算)
Text3.Text = MaxGongYueShu(num)
End Sub
在command1的单击事件中,输入如下编码:
dim i,a,b as integer;
a=val(text1.text)
b=val(text2.text)
if a*b=0 then
if a<>0 then
text3.text=str(a)
else
text3.text=str(b)
end if
text4.text="0"
exit()
endif
while(a<>0)
i=a mod b
a=b
b=i
wend
text3.text=str(b)
text4.text=str(val(text1.text)*val(text2.text)\b)
上一个:VB 怎样验证SQL数据表中的用户登录
下一个:求VB进度条的详细使用方法