为什么我需要创建一个Random类的实例,如果我想创建1到100之间的随机数....就像
Random rand = new Random();
rand.Next(1,100);
Run Code Online (Sandbox Code Playgroud)
Random类是否有任何静态函数来做同样的事情?喜欢...
Random.Next(1,100);
Run Code Online (Sandbox Code Playgroud)
我不想不必要地创建一个实例
在寻找生成真正随机数的最佳尝试时,我偶然发现了这个代码示例.
在这个片段上寻找意见.
using System;
using System.Security.Cryptography;
private static int NextInt(int min, int max)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buffer = new byte[4];
rng.GetBytes(buffer);
int result = BitConverter.ToInt32(buffer, 0);
return new Random(result).Next(min, max);
}
Run Code Online (Sandbox Code Playgroud)
资料来源:http://www.vcskicks.com/code-snippet/rng-int.php
这比使用滴答计数种子更受欢迎,例如:
Random rand = new Random(Environment.TickCount);
rand.Next(min, max);
Run Code Online (Sandbox Code Playgroud)
注意:
我不是在寻找第三方随机数据提供者,例如Random.org,因为这种依赖对应用程序来说是不现实的.
我在Microsoft Visual C#2008 Express中工作.
我找到了这段代码:
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
Run Code Online (Sandbox Code Playgroud)
问题是我运行了100多次,当我的min = 0和max = 1时,它总是给我相同的答案.我每次都得到0.(我创建了一个测试函数来运行它 - 真的 - 我每次都得到0).我很难相信这是巧合...我还能做些什么来检查或测试这个?(我确实重新进行了测试,min = 0和max = 10,前50次,结果总是"5",第二次50次,结果总是"9".
?? 我需要一些更随意随意的东西......
-Adeena
有问题在循环中生成随机数.可以通过使用Thread.Sleep绕过它但是在更优雅的解决方案之后.
for ...
Random r = new Random();
string += r.Next(4);
Run Code Online (Sandbox Code Playgroud)
最终将以11111 ... 222 ...等结束
建议?
您好我在使用C#生成随机数时遇到一些问题现在我有了这个功能.
public Color getRandomColor()
{
Color1 = new Random().Next(new Random().Next(0, 100), new Random().Next(200, 255));
Color2 = new Random().Next(new Random().Next(0, 100), new Random().Next(200, 255));
Color3 = new Random().Next(new Random().Next(0, 100), new Random().Next(200, 255));
Color color = Color.FromArgb(Color1, Color2, Color3);
Console.WriteLine("R: " + Color1 + " G: " + Color2 + " B: " + Color3 + " = " + color.Name);
return color;
}
Run Code Online (Sandbox Code Playgroud)
现在你可能会注意到那里有很多新的Random(),这是因为我想要清除它可能是同一个实例错误的概率.
我现在运行这个功能8次,几次.现在这里是出局.
R: 65 G: 65 B: 65 = ff414141
R: 242 G: 242 B: 242 = …Run Code Online (Sandbox Code Playgroud)