2012-08-03 66 views
2

我有以下代碼。隨機r的作品,並得到我約10%,如果。然而,rr似乎並不奏效。它總是返回0.我做錯了什麼?嵌套隨機發生器不是隨機的

我想在兩個選擇中隨機選擇10%的時間。這是在一個asp.net應用程序。代碼在點擊按鈕時執行。

 Random r = new Random(); 
     Random rr = new Random(); 

     int randomnum = r.Next(0, 100); 
     if (randomnum <= 10) 
     { 

      int randompick = rr.Next(0, 2); 
      if (randompick == 0) 
      { 
+7

難道你只是使用相同的隨機選擇對象? – 2012-08-03 23:21:35

+1

** NB ** _「默認種子值是從系統時鐘派生的,並具有有限分辨率。因此,通過調用默認構造函數緊密連續創建的不同Random對象將具有相同的默認種子值,並且,因此,將產生相同的隨機數集合。「_ http://msdn.microsoft.com/en-us/library/h343ddh9.aspx – 2012-08-03 23:22:32

+1

」隨機「類的良好經驗法則:不要重新構造每次你需要一個號碼時,RNG。創建一個'Random',將其存儲在一個具有類作用域的變量中,只要需要一個數字,就調用'r.Next(X,Y)'。 – 2012-08-03 23:24:06

回答

4

如果你很高興與外循環的隨機性,考慮

int randompick = randomnum % 2; 

代替嵌套的隨機對象。

1

你可以使用相同的Random對象隨機選擇,對吧?

+0

不好意思Sam現在我看着它Babak的答案有點優雅。但我非常感謝你的回答。 – Tigran 2012-08-03 23:33:53

+0

謝謝@Tigran! – 2012-08-03 23:34:48

0

如上所述,您應該只使用一個僞隨機流並僅實例化一次。我會沿着這些線構建我的解決方案:

class SomeWidget 
{ 
    private static Random rng ; 

    static SomeWidget() 
    { 
     rng = new Random() ; 
     return ; 
    } 

    public SomeWidget() 
    { 
     return ; 
    } 

    public int DoOneThing90PercentOfTheTimeAndSomethingElseTheRestOfTheTime() 
    { 
     int rc ; 
     int n = rng.Next() % 10 ; // get a number in the range 0 - 9 inclusive. 
     if (n != 0 ) // compare to whatever value you wish: 0, 1, 2, 3, 4, 5, 6, 8 or 9. It makes no nevermind 
     { 
      rc = TheNinetyPercentSolution() ; 
     } 
     else 
     { 
      rc = TheTenPercentSolution() ; 
     } 
     return rc ; 
    } 

    private int TheTenPercentSolution() 
    { 
     int rc ; 
     int n = rng.Next() % 2 ; 
     if (n == 0) 
     { 
      rc = DoOneThing() ; 
     } 
     else 
     { 
      rc = DoAnotherThing() ; 
     } 
     return rc ; 
    } 

    private int DoOneThing() 
    { 
     return 1; 
    } 

    private int DoAnotherThing() 
    { 
     return 2 ; 
    } 

    private int TheNinetyPercentSolution() 
    { 
     return 3 ; 
    } 

}