我想我会在这个问题上大吃一惊,因为我刚刚扩展了@dbasnett 的答案以制作一个不错的通用生成器。
注意:我使用了 Decimal 但 Double 可以替换为输出,没有任何问题。
''' <summary>
''' Random Decimal generator with variable precision"
''' </summary>
''' <param name="L">Minimum Value</param>
''' <param name="U">Maximum Value</param>
''' <param name="P">Precision</param>
''' <returns>Decimal</returns>
''' <remarks></remarks>
Private Function DRandom(L As Integer, U As Integer, P As Integer) As Decimal
Dim Rand As New Random
Dim Upper As String = U.ToString
Dim Precision As String = "1"
For I = 0 To P
If I > 0 Then
If I = P Then
Upper = Upper + "1"
Else
Upper = Upper + "0"
End If
Precision = Precision + "0"
End If
Next
Return Rand.Next(L, Upper.toInteger) / Precision.toInteger
End Function
使用我的通用 toInteger 扩展:
''' <summary>
''' Handles conversion of variable to Integer.
''' </summary>
''' <param name="X"></param>
''' <param name="I">Returned if conversion fails.</param>
''' <returns>Signed 32bit Integer</returns>
''' <remarks></remarks>
<Runtime.CompilerServices.Extension()> _
Public Function toInteger(Of T)(ByRef X As T, Optional I As Integer = 0) As Integer
Dim S As String = X.ToString
Try
If S = String.Empty Then
Return I
Else
Return Integer.Parse(S)
End If
Catch
Dim result As String = String.Empty
Dim ReturnInt As Integer
Dim Parsed As Byte
For Each Character In S.ToCharArray
If Character = "-" Then
If S.Substring(0, 1).ToString <> "-" Then
result = Character + result
End If
End If
If Character = "." Then
Exit For
End If
If Byte.TryParse(Character, Parsed) Then
result = result + Parsed.ToString
End If
Next
If result <> String.Empty Then
If Integer.TryParse(result, ReturnInt) Then
Return Integer.Parse(ReturnInt)
Else
If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
Return Integer.MaxValue
ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
Return Integer.MinValue
Else
Return I
End If
End If
Else
Return I
End If
End Try
End Function
该生成器采用可变精度,并允许您在代码中选择上限和下限允许(在我看来)随机数生成器的最大可重用性。
希望这对人们有所帮助。