2011-11-06 51 views
1

我试图用c#做某种游戏,它的loto游戏有10列。计算机有产生6个号码,以填补10列,我的代码是这样的:c中的Loto游戏#

public static int[] Get() 
    { 
     int[] a = new int[6]; 
     System.Random r = new System.Random(); 
     bool flag; int val; 
     for (int i = 0; i < a.Length; ++i) 
     { 
      flag = false; 
      do 
      { 
       val = r.Next(1, 50); 
       for (int k = 0; k < i; ++k)  
        if (a[k] == a[i]) 
        { 
         flag = true; 
         break; 
        } 
       a[i] = val; 
      } while (flag); 
     } 
     return a; 
    } 
    public static void Main() 
    { 
     int[] a; 
     for (int i = 0; i < 10; ++i) 
     { 
      a = Get(); 
      foreach (int x in a) 
       Console.Write("{0} ", x); 
      Console.WriteLine(); 
     } 
    } 

但它提供了相同的结果,像

4 44 19 44 22 7 
4 44 19 44 22 7 
4 44 19 44 22 7 
4 44 19 44 22 7 
4 44 19 44 22 7 
4 44 19 44 22 7 
4 44 19 44 22 7 
4 44 19 44 22 7 
4 44 19 44 22 7 
22 29 28 15 33 6 

有啥错在我的代码。
谢谢

+0

[偶然的遭遇并非如此随机](http://stackoverflow.com/questions/2727538/random-encounter-not-so-random) –

回答

1

由于随机类的原因,其默认方法需要从计算机的当前时间开始计算,因此您在同一时间调用该方法,结果相同。您可以修改代码如下

public static int[] Get(System.Random r) 
    { 
     int[] a = new int[6]; 
     bool flag; 
     int val; 

     for (int i = 0; i < a.Length; ++i) 
     { 
      flag = false; 

      do 
      { 
       val = r.Next(1, 50); 
       for (int k = 0; k < i; ++k) 
        if (a[k] == a[i]) 
        { 
         flag = true; 
         break; 
        } 
       a[i] = val; 
      } while (flag); 
     } 

     return a; 
    } 


    public static void Main() 
    { 
     int[] a; 
     System.Random r = new System.Random(); 

     for (int i = 0; i < 10; ++i) 
     { 
      a = Get(r); 

      foreach (int x in a) 
       Console.Write("{0} ", x); 
      Console.WriteLine(); 
     } 
    } 
+0

是其确定的可能重复现在:) – user1031757

4

Random类从系统时间播种。
当您连续拍摄很多Random时,它们最终会同时创建并使用相同的种子。

您应该在调用Get()时重复使用Random实例。