English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

各位達人好:
我不是要做作業,只是程式片段需要
「不重複的亂數」
網路上的解答跑不對(尤其雅虎部落格那幾篇)
希望有高手幫我寫成函數,格式如下:
public function GetNonRepeatingNumber(byval LowerNo as Long, UpperNo as Long, TotalGenerated as Long)

請使用Visual basic 6(不要用.net)

2007-01-24 08:30:33 · 2 個解答 · 發問者 ? 7 in 電腦與網際網路 程式設計

2 個解答


Public Function GetNonRepeatingNumber(ByVal LowerNo As Long, ByVal UpperNo As Long, ByVal TotalGenerated As Long)
If UpperNo < LowerNo Or UpperNo - LowerNo + 1 < TotalGenerated Or TotalGenerated < 1 Then
ReDim A(1): A(1) = "輸入錯誤"
Else
ReDim A(1 To TotalGenerated), B(LowerNo To UpperNo) As Boolean
Dim I&, N&

Randomize
For I = 1 To TotalGenerated
Do
N = Int(Rnd * (UpperNo - LowerNo + 1) + LowerNo)
Loop Until Not B(N)
B(N) = True: A(I) = N
Next
End If
GetNonRepeatingNumber = A
End Function
'使用方法(隨機找出5個1~10之間不重複的整數)
Private Sub Command1_Click()
Dim I&, A

A = GetNonRepeatingNumber(1, 10, 5)
For I = 1 To UBound(A)
Print A(I)
Next
End Sub

2007-01-24 14:56:59 · answer #1 · answered by W.J.S. 7 · 0 0

真是好大的口氣啊,不妨把你認為錯的貼出來研究研究...
我部落格也寫過一篇,不知你看過了嗎?
Private Sub 不重複之亂數_範例(ByVal 範圍上限 As Integer, ByVal 應取數 As Integer)
ReDim n(應取數) As Integer
Dim i As Integer, 總數 As Integer, 亂數 As Integer
Dim 是否重複 As Boolean
Dim s As String
是否重複 = False: 總數 = 0
Randomize
Do
亂數 = Fix(Rnd() * 範圍上限) + 1
For i = 0 To 應取數 - 1
If n(i) = 亂數 Then
是否重複 = True
End If
Next
If 是否重複 = False Then
n(總數) = 亂數
s = s & vbCrLf & "第" & 總數 + 1 & " 個數字為" & n(總數)
總數 = 總數 + 1
Else
是否重複 = False
End If
Loop Until 總數 = 應取數
MsgBox (s)
End Sub

雖然你的輸入有三個參數,但那又怎樣呢?
想取亂數於範圍間?
upperNo = 範圍上限
lowerNo = 範圍下限
亂數 = Fix(Rnd() * (範圍上限 - 範圍下限) ) + 範圍下限
不就解決了嗎?

2007-01-25 08:17:55 · answer #2 · answered by 黃俊霖 7 · 0 0

fedest.com, questions and answers