【发布时间】:2011-04-03 11:32:23
【问题描述】:
我正在尝试生成一个随机长度的字符串,该字符串由随机 chars 组成。
为此,我有以下代码:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
MyString test = new MyString();
test.Random();
Console.WriteLine(test.Value);
}
Console.ReadLine();
}
}
public class MyString
{
private string value = string.Empty;
private Random r = new Random();
public string Value
{
get { return this.value; }
set { this.value = value; }
}
public void Random()
{
int length = (r.Next() % (100)) + 1;
for(int i = 0; i < length; i++)
{
value = value + RandomChar();
}
}
public char RandomChar()
{
// 32 to 126
int c = (r.Next() % 95) + 32;
char ch = (char)c;
return ch;
}
}
现在,让我们看一下输出的一部分:
如您所见,输出远非随机,它包含大量重复的字符串。这怎么可能,我该如何解决?
【问题讨论】:
-
这就是随机性,你永远无法知道它是否不是随机的。
-
这张图片很难看懂。
-
Random.Next 有 3 个重载,您至少应该对其中一个感兴趣:msdn.microsoft.com/en-us/library/13td4hz1.aspx
-
@NullUserException:不管是否是面无表情的幽默,有一些方法可以获得足够的分布/独立性,我们不在乎区分随机和难以预测。