vb.net 生成2位小数的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17134403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:55:40  来源:igfitidea点击:

Generate random number to 2 decimal places

vb.net

提问by finisterre

blah = CInt(Int((7 * Rnd()) + 0))

Generates a random integer between 0 and 6.

生成 0 到 6 之间的随机整数。

How can I modify this to give me a random number with 2 decimal places, still between 0 and 6?

如何修改它以给我一个带有 2 个小数位的随机数,仍然在 0 到 6 之间?

As suggested below, I'm now using this code, and it seems to work:

正如下面所建议的,我现在正在使用此代码,它似乎有效:

Dim prng As New Random

Private Function aRand() As Double
    Return Math.Round(prng.Next(0, 601) / 100, 2)
End Function

currentApp.statements(Pick, 7) = aRand()
currentApp.statements(Pick, 8) = aRand()

Thanks for all the suggestions.

感谢所有的建议。

采纳答案by dbasnett

Like this

像这样

Dim prng As New Random

Private Function aRand() As Double
    Return prng.Next(0, 601) / 100
End Function

note that the location of the random.

注意位置随机。

Your code would look like

你的代码看起来像

    currentApp.statements(Pick, 7) = aRand()
    currentApp.statements(Pick, 8) = aRand()

回答by Steve

The OP says between 0.00 and 6.00, so I believe that the advice from @HansPassant is the best to try but enlarging the upper limit to 601 ( if he means the limits are inclusive of course)

OP 说between 0.00 and 6.00,所以我相信@HansPassant 的建议是最好的尝试,但将上限扩大到 601(如果他的意思是限制当然包括在内)

Dim rnd As New Random
Dim x As Integer = rnd.Next(0, 601)
Dim d = x / 100
Console.WriteLine(d)

回答by Neolisk

Based on @Steve's answer, here is a generic implementation:

根据@Steve 的回答,这是一个通用实现:

Function RandomDouble(maxValue As Integer, precision As Integer) As Double
  Static rnd As New Random
  Dim scale As Double = 10 ^ precision
  Dim x As Integer = rnd.Next(0, maxValue * scale + 1)
  Return x / scale
End Function

And the usage (tested in an empty console app, sub main):

和用法(在一个空的控制台应用程序中测试,sub main):

Dim dbl As Double = RandomDouble(6, 2)
Debug.WriteLine(dbl)

So you can reuse it like this:

所以你可以像这样重用它:

currentApp.statements(Pick, 7) = RandomDouble(6, 2)
currentApp.statements(Pick, 8) = RandomDouble(6, 2)

Or with DRY principle (=don't repeat yourself):

或者使用DRY 原则(=不要重复自己)

For i As Integer = 7 To 8
  currentApp.statements(Pick, i) = RandomDouble(6, 2)
Next

回答by ARidder101

I thought I would throw my hat in the ring on this question because I just expanded on @dbasnett answer to make a nice generic generator.

我想我会在这个问题上大放异彩,因为我只是扩展了@dbasnett 的答案以制作一个不错的通用生成器。

Note: I used Decimal but Double can be substituted as the output with no seen issues.

注意:我使用了 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

With my generic toInteger extension:

使用我的通用 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

This generator takes a variable precision as well as letting you choose in the code what the upper and lower bounds are allowing for (in my opinion) maximum re-usability for a random number generator.

该生成器采用可变精度,并让您在代码中选择上限和下限允许(在我看来)随机数生成器的最大可重用性。

Hope this helps people.

希望这可以帮助人们。