猿问

如何清除系统.随机种子?

我使用 System.Random 函数为随机数创建/生成种子,然后使用 Next() 为后续数字创建/生成种子,但与 c++ 非常相似,“rng”每次都能为我提供相同的随机数结果。但是在c ++中,这是通过清除c ++中的种子来解决的,所以我想知道这在c#中是否也可能?


哆啦的时光机
浏览 86回答 1
1回答

GCT1015

您很可能每次都使用一个新实例。不应以可重复方式实例化。Randomnew Random(seed_here)Random r = new Random(); //Do this once - keep it as a (static if needed) class field&nbsp;&nbsp; &nbsp; &nbsp;for (int i = 0; i < 10; i++) {&nbsp; &nbsp; &nbsp;Console.WriteLine($"{r.Next()}");}更新下面是一个更复杂的示例:class MyClass{&nbsp; &nbsp; //You should use a better seed, 1234 is here just for the example&nbsp; &nbsp; Random r1 = new Random(1234); // You may even make it `static readonly`&nbsp; &nbsp; public void BadMethod()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // new Random everytime we call the method = bad (in most cases)&nbsp; &nbsp; &nbsp; &nbsp; Random r2 = new Random(1234);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 3; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine($"{i + 1}. {r2.Next()}");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void GoodMethod()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 3; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine($"{i+1}. {r1.Next()}");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}class Program{&nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var m = new MyClass();&nbsp; &nbsp; &nbsp; &nbsp; m.BadMethod();&nbsp; &nbsp; &nbsp; &nbsp; m.BadMethod();&nbsp; &nbsp; &nbsp; &nbsp; m.GoodMethod();&nbsp; &nbsp; &nbsp; &nbsp; m.GoodMethod();&nbsp; &nbsp; }}输出1. 8570198772. 19239294523. 685483091&nbsp; &nbsp;&nbsp;1. 857019877&nbsp; <--- Repeats2. 19239294523. 6854830911. 8570198772. 19239294523. 6854830911. 2033103372 <--- Phew! It's a new number2. 7289333123. 2037485757
随时随地看视频慕课网APP
我要回答