vb.net .NET - 如何在具有特定步长的范围内生成随机数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13231247/
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-09 16:24:18  来源:igfitidea点击:

.NET - How to generate random numbers in a range with a certain step size?

vb.netrandomrange

提问by bluebox

I'd like to generate random numbers in a range (say between 0 and 1) - but with a certain step size (say 0.05). There's a python functionthat does exactly that:

我想生成一个范围内的随机数(比如在 0 和 1 之间) - 但有一定的步长(比如 0.05)。有一个python 函数可以做到这一点:

random.randrange ( [start,] stop [,step] )

So my problem is not how to generate random numbers in a range - instead I need a way to do this with a certain step size. How can this be done in .NET?

所以我的问题不是如何在一个范围内生成随机数 - 相反,我需要一种方法来以一定的步长来做到这一点。如何在 .NET 中做到这一点?

回答by Patrick McDonald

You could generate a random integer between 0 and 20 and divide the result by 20

您可以生成 0 到 20 之间的随机整数并将结果除以 20

Dim rnd = New Random()
Dim nextValue = rnd.Next(21) / 20

This will give you a random number between 0 and 1 (inclusive) in 0.05 increments

这将为您提供 0 到 1(含)之间的随机数,增量为 0.05

回答by Nianios

You can try something like that:

你可以尝试这样的事情:

  Dim objRandom As New System.Random
  Label1.Text = Math.Round(objRandom.NextDouble() * 2, 1) / 2

So you create a random double and you round it to one digit (example: 0.8).
Then you divided it with 2 and you get what you want

因此,您创建了一个随机双精度数并将其四舍五入为一位数(例如:0.8)。
然后你将它除以 2 得到你想要的