class roll
{
public static void Main()
{
int one=0,
two=0,
three=0,
four=0,
five=0,
six=0,
time=one+two+three+four+five+six;
//System.Random rnd=new System.Random();//奇怪地方1
while(time<100)
{
System.Random rnd=new System.Random();//奇怪地方2
int roll=(int) rnd.Next(1,7);
System.Console.WriteLine("Roll {0} is {1}",time+1,roll);
switch(roll)
{
case 1:one++;break;
case 2:two++;break;
case 3:three++;break;
case 4:four++;break;   
case 5:five++;break;
case 6:six++;break;
default:System.Console.WriteLine("not 1 to 6");break;
}
               time=one+two+three+four+five+six;
}
System.Console.WriteLine("print one point time:{0}",one);
System.Console.WriteLine("print two point time:{0}",two);
System.Console.WriteLine("print three point time:{0}",three);
System.Console.WriteLine("print four point time:{0}",four);
System.Console.WriteLine("print five point time:{0}",five);
System.Console.WriteLine("print six point time:{0}",six);
}
}上面是个简单的Roll程序,现在运行则结果很集中
print one point time:0
print two point time:0
print three point time:0
print four point time:74
print five point time:26
print six point time:0
如果现在单步执行,则结果分布均匀,达到预期效果
print one point time:18
print two point time:17
print three point time:15
print four point time:15
print five point time:17
print six point time:18
当把奇怪地方2注释掉,用奇怪地方1运行,则结果分布正常
print one point time:18
print two point time:20
print three point time:12
print four point time:18
print five point time:17
print six point time:15
谁能帮我详细解释一下,谢谢GGJJDDMM帮忙!!

解决方案 »

  1.   

    奇怪地方2   重新new了一个对象,没有提供种子,每次next()返回的都是同一个数。 Random 类并不是真正的随机数,提供一个特定种子后会 产生相同数列。
      

  2.   

    一点儿也不奇怪,Random本来就是这样的。所以只应该创建一个Random实例,之后不断的Next。而Random的种子应该用创建时时间的微秒值。
      

  3.   

    生成的数字分布均匀;每个数字返回的可能性均相等。
    默认种子值是从系统时钟派生而来的。但是,在高性能系统上生成随机数时,系统时钟值可能不会产生预期的行为。
    如果应用程序需要不同的随机数序列,则使用不同的种子值重复调用此构造函数。一种产生唯一种子值的方法是使它与时间相关。
    Random rdm1 = new Random(unchecked((int)DateTime.Now.Ticks));
      

  4.   

    谢谢的各位,你们一说我明白了些,CSDN还真是好地方,这么多热心人~~以后我的菜鸟问题还要各位大虾帮忙!!