产生随机数 奇偶数排序 素数求和

本文是为了解决yybbhh123的问题而专门写的代码(http://topic.csdn.net/u/20100514/09/075187a1-aebe-4811-804a-44430a9636f7.html?60289)。具体问题:利用随机函数产生80个10~99之间的随机整数,将其中的偶数按由小到大的数序排列并输出,将奇数按由大到小的数序排列并输出;在产生的80个随机整数中,找出其中的素数,并将这些素数求和。

Option Explicit '利用随机函数产生80个10~99之间的随机整数 myArray存储随机数 Num随机数个数 Seed种子 Private Sub CreateRndArray(ByRef myArray() As Long, Num As Long, Optional ByVal Seed As Long = 65535) Dim i As Long, rndNum As Long i = 0 Call Rnd(Seed) Do While i < Num rndNum = CLng(Rnd * 100) If rndNum >= 10 And rndNum <= 99 Then i = i + 1 myArray(i) = rndNum End If Loop End Sub '由原数组中的数据产生两个奇偶数组 Private Sub splitArray(ByRef tmpArray() As Long, ByRef OddArray() As Long, ByRef EvenArray() As Long) Dim iMin As Long, iMax As Long, i As Long Dim iOdd As Long, iEven As Long iMin = LBound(tmpArray) iMax = UBound(tmpArray) iOdd = 0 iEven = 0 For i = iMin To iMax If tmpArray(i) Mod 2 = 0 Then iEven = iEven + 1 ReDim Preserve EvenArray(1 To iEven) EvenArray(iEven) = tmpArray(i) Else iOdd = iOdd + 1 ReDim Preserve OddArray(1 To iOdd) OddArray(iOdd) = tmpArray(i) End If Next i End Sub '排序 tmpArray数组 Ascend升序降序排列标识 Private Sub Sort(ByRef tmpArray() As Long, Optional Ascend As Boolean = True) Dim iMin As Long, iMax As Long Dim i As Long, j As Long, k As Long Dim lngTmp As Long iMin = LBound(tmpArray) iMax = UBound(tmpArray) For i = iMin To iMax - 1 k = i For j = i + 1 To iMax If Ascend Then If tmpArray(k) > tmpArray(j) Then k = j Else If tmpArray(k) < tmpArray(j) Then k = j End If Next j If k <> i Then lngTmp = tmpArray(i): tmpArray(i) = tmpArray(k): tmpArray(k) = lngTmp End If Next i End Sub '素数判断 Private Function IsPrime(ByVal vData As Long) As Boolean Dim i As Long, iSqrt As Long IsPrime = False If vData <= 1 Then Exit Function iSqrt = CLng(Sqr(vData)) For i = 2 To iSqrt If vData Mod i = 0 Then Exit For Next i If i <= iSqrt Then IsPrime = True End Function Private Sub Command1_Click() Const Max As Long = 80 '随机数个数 Dim myArray(1 To Max) As Long '随机数组 Dim Odds() As Long '奇数 Dim Evens() As Long '偶数 Dim PrimeSum As Long '素数和 Dim i As Long Call CreateRndArray(myArray, Max) Call splitArray(myArray, Odds, Evens) Call Sort(Odds, False) Call Sort(Evens, True) PrimeSum = 0 For i = 1 To Max If IsPrime(myArray(i)) Then PrimeSum = PrimeSum + myArray(i) Next i Call PrintToText(myArray, Text1) Call PrintToText(Odds, Text2) Call PrintToText(Evens, Text3) Label4.Caption = "素数和:" & CStr(PrimeSum) End Sub Private Sub PrintToText(ByRef tmpArray() As Long, ByRef txtBox As TextBox) Dim iTmp As Variant For Each iTmp In tmpArray txtBox.Text = txtBox.Text & CStr(iTmp) & vbCrLf Next End Sub Private Sub Form_Load() Text1.Text = "" Text2.Text = "" Text3.Text = "" End Sub

文本框的mutiLine属性为True

你可能感兴趣的:(textbox,function,command,each,存储,2010)