2015-07-19 86 views
0

所以我剛剛開始學習C#,並且我在本練習中得到了N次滾動模,然後打印每個滾動的次數。我得到了答案,但是,我的問題在於在循環前和循環中實例化一個Random數字對象。在for循環之前實例化和在for循環中實例化之間的區別

我的代碼是這樣的(這是循環之前實例化):

static void DiceRoll(int RollTimes) 
    { 

     int roll = 0; 

     int counter1 = 0; 
     int counter2 = 0; 
     int counter3 = 0; 
     int counter4 = 0; 
     int counter5 = 0; 
     int counter6 = 0; 

     Random rnd = new Random(); 

     for (int ctr = 0; ctr < RollTimes; ctr++) 
     { 
      roll = 0; 
      roll = (int)rnd.Next(1, 7); 

      switch (roll) 
      { 
       case 1: 
        counter1++; 
        break; 

       case 2: 
        counter2++; 
        break; 

       case 3: 
        counter3++; 
        break; 

       case 4: 
        counter4++; 
        break; 

       case 5: 
        counter5++; 
        break; 

       case 6: 
        counter6++; 
        break; 
      } 
     } 

     Console.WriteLine("1 is rolled {0} times.", counter1); 
     Console.WriteLine("2 is rolled {0} times.", counter2); 
     Console.WriteLine("3 is rolled {0} times.", counter3); 
     Console.WriteLine("4 is rolled {0} times.", counter4); 
     Console.WriteLine("5 is rolled {0} times.", counter5); 
     Console.WriteLine("6 is rolled {0} times.", counter6); 
    } 

,結果是這樣的:

1 is rolled A times. 
2 is rolled B times. 
3 is rolled C times. 
4 is rolled D times. 
5 is rolled E times. 
6 is rolled F times. 

我之前正確的,實例化線(Random rnd = new Random(); )在循環中。

for (int ctr = 0; ctr < RollTimes; ctr++) 
     { 
      roll = 0; 
      roll = (int)rnd.Next(1, 7); 
      Random rnd = new Random(); 
      // rest of the code 

那麼結果(任意):

1 is rolled (N) times. 
2 is rolled (N) times. 
3 is rolled (N) times. 
4 is rolled (N) times. 
5 is rolled (N) times. 
6 is rolled (N) times. 

有人可以解釋爲什麼實例的位置改變的結果告訴我嗎?謝謝!

回答

0

想法是,隨機對象實際上並不是「隨機的」,說實話,現實中沒有這樣的事情,除了量子力學。好的,回到你的問題,讓你明白的是,在幕後有一系列(非常複雜的),對於給定的起始值(默認值爲零),下一個值是計算機內部抓取下一個系列值。內部系列的複雜性讓你感覺價值實際上是隨機的。每當你使用相同的種子實例化一個新的Random對象時,你將擁有相同的系列值。最好的模式是使用重載的構造函數,該構造函數接受一個種子併爲種子值使用某種東西limetime.Now.Ticks並嘗試緩存您的隨機對象。

所以答案是在循環外部創建一個實例,甚至更好地爲每個實例化使用不同的種子。

相關問題