Max=a(i)
End If
If Min>a(i) Then ’求最小数
Min=a(i)
End if
Sum=Sum+a(i) ’求和
Next i
Avg=Sum/10 ’求平均数
Print “最大数:”;Max;“最小数:”;Min;“和:”;Sum;“平均数:”;Avg
End Sub
二、求阶乘
例题:求10!.
Private Sub Command1_Click()
Dim Sum As Long, i As Integer
Sum=1
For i= 1 To 10
Sum=Sum*i
Next i
Print “10!=”;Sum
End Sub
三、求最大公约数
例题:求M和N两个数的最大公约数。
Private Sub Command1_Click()
Dim M As Integer, N As Integer, R As Integer
M=36:N=24
Do
R=M Mod N
M=N
N=R
Loop While R<>0 ’或Loop Until R=0
Print "M和N的最大公约数为:";M
End Sub
四、求素数
例题:求100—200之间的所有素数,并按每行5个元素格式输入所有素数。
Private Sub Command1_Click()
Dim n As Integer ,i As Integer j As Integer
For n = 100 To 200
For i = 2 To n-1 ’n-1可以是n/2,也可以是Sqr(n)形式If n
Mod i =0 Then Exit For
Next i
If i>n-1 Then
j=j+1 ’统计素数个数
Print n;
If j Mod 5 =0 Then Print ’输出5个数换行
End If
Next n
End Sub
判断素数的函数过程:
Function Prime (x As Integer)As Boolean
Dim I As Integer
For I = 2 To Sqr(x)
If x Mod I= 0 Then
Prime=False
End If
Next I
Prime=True
End Function
五、求水仙花数(拆数法)
例题:求100—999之间的所有水仙花数,并将所有水仙花数在文本框中显示。所谓水仙花数:即153=1^3+5^3+3^3条件成立。
方法1:(数值型:使用运算符Mod 和\)
Private Sub Command1_Click()
Dim i As Integer ,a As Integer ,b As Integer ,c As Integer
For i = 100 To 999
a=i\100’取百位数
b=i\10 Mod 10 ’取十位数
c=i Mod 10 ’取个位数
If i=a^3+b^3+c^3 Then
Text1.Text=Text1.Text & i & Space(2)
End If
Next i
End Sub
方法2:(字符型:使用函数Mid、Val和CStr)
Private Sub Command1_Click()
Dim i As Integer ,a As Integer ,b As Integer ,c As Integer
For i = 100 To 999
a= Val(Mid(CStr(i),1,1))’取百位数
b= Val(Mid(CStr(i),2,1))’取十位数
c= Val(Mid(CStr(i),3,1))’取个位数
If i=a^3+b^3+c^3 Then
Text1.Text=Text1.Text & i & Space(2)
End If
Next i
End Sub
六、排序问题
例题:随机产生10个两位整数,并存入数据a中,然后将这10个元素从小到大排序(或从大到小),并将排序号的数组显示在文本框中。
方法1:选择排序
Private Sub Command1_Click()
Dim a(10) As Integer, i As Integer, j As Integer ,temp As Integer
For i= 1 To 10
a(i)=Int(Rnd*90)+10 ’产生10—99之间的随机整数
Next i
For i= 1 To 9 ’比较n-1轮
For j = i+1 To 10 ’每一轮比较几次
If a(i)>a(j) Then ’从大到小:a(i)temp=a(i)
a(i)=a(j)
a(j)=temp
End If
Next j
Next i
For i =1 To 10
Text1.Text=Text1.Text & a(i) & space(2)
Next i
End Sub
方法2:直接插入排序
Private Sub Command1_Click()
Dim a(10) As Integer, i As Integer, j As Integer ,temp As Integer
Dim Pointer As Integer
For i= 1 To 10
a(i)=Int(Rnd*90)+10 ’产生10—99之间的随机整数
Next i
For i= 1 To 9 ’比较n-1轮