VB二级考试练习课件.docx
'L编写函数fun,函数的功能是:求一个四位数的各位数字的立方和 Private Sub command1 click ()Print fun (1234) End SubPrivate Function fun(n As Integer) As LongDim d As Integer, i As Integer, s As Integer For i = 1 To 4d = Vai (Mid(CStr (n), i, 1)s = s + d - 3 Next i fun = s End Function'2,编写函数fun函数的功能是:求1到100之前所有偶数之积 Private Sub Commandl_Click ()Print fun (100) End SubPrivate Function fun(n As Integer) As Double Dim i As Integer fun 二 1For i = 1 To 100If i Mod 2=0 Then fun = fun * i Next i End Function'4.通用过程fun中实现,计算出0T00范围内所有的偶数的平方和 Private Sub Command1 Click() Print fun ()textl. text=d SaveDateEnd SubPrivate Function fun() Dim sum As DoubleFor i = 0 To 100 Step 2 sum = sum + i - 2Next i fun = sum End Function'3.编写函数fun,函数的功能是:计算n门课程的平均值,计算结果作为函数值返回 '例如 假设有5门课程的成绩是:92 76 69 58 88,那么函数的值为76.6 Option Base 1Private Sub Commandl_Click()Dim a(5) As IntegerFor i = 1 To 5a(i) = Int (100 * Rnd + 1)Textl = Textl & a(i) & (内有空格) Next i Print fun(a, 5) End SubPrivate Function fun(a() As Integer, n As Integer) As Double Dim s As Integer For i = 1 To ns = s + a(i) Next i fun = s / n End Function'5.编写函数fun,函数的功能是:计算并输出给定整数n的所有因子之和(不包括1与自 身),规定N的值不大于1000 Private Sub Commandl Click() Print fun (12) End SubPrivate Function fun(n As Integer) As Integer Dim sum As Integer, i As Integer For i = 2 To n - 1If n Mod i = 0 Then sum = sum + i Next i fun = sum End Function'7.将字符串逆序的函数reverseOption Explicit(变量声明语句可无)Private Sub Commandl_Click () Text2 = reverse (Textl) End SubPrivate Function reverse (s As String) As String Dim i As Integer For i = 1 To Len(s)reverse = Mid(s, i, 1) & reverse Next i End Function'6.判断一个数是否是素数的函数prime Private Sub Commandl Click ()Dim a As Integer a = Vai (Textl)If prime(a) ThenPrint 不是素数Elself prime(a) = False ThenPrint 是素数End IfEnd SubPrivate Function prime(n As Integer) As BooleanDim i As IntegerIf n = 2 Then Exit FunctionFor i = 2 To n - 1If n Mod i = 0 Thenprime = TrueElself n Mod i <> 0 ThenExit FunctionEnd IfNext iEnd Function'8.求两个数的最大公约数的函数gcdPrivate Sub Commandl_Click ()Dim a As Integer, b As Integer, c As Integera = Vai (Textl)b = Vai (Text2) c = a * bText3 = CStr(c / gcd (a, b)End SubPrivate Function gcd(a As Integer, b As Integer) As Integer Dim r As IntegerDor = a Mod ba = bb = rLoop Until r = 0gcd 二 aEnd Function9.求阶乘n!的值的函数fact Private Sub Commandl Click () Dim a As Integer, b As Long a = Vai (Textl) b = fact(a) Text2 = b End SubPrivate Function fact(a As Integer) As LongDim i As Integer fact = 1For i = 1 To afact = fact * iNext iEnd Function,10.求一维数组元素之和的过程totalOption Base 1Private Sub Commandl_Click()Dim a(10) As IntegerDim i As Integer, sum As IntegerFor i = 1 To 10a(i)= Int(Rnd * 90) + 10Textl = Textl & a(i) & Next iCall total (a, sum)Text2 = sumEnd SubPrivate Function total(a() As Integer, sum As Integer)Dim i As IntegerFor i = 1 To UBound (a)sum = sum + a(i)Next iEnd Function