为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
哆啦的时光机 2022-08-20 15:28:33
我使用 System.Random 函数为随机数创建/生成种子,然后使用 Next() 为后续数字创建/生成种子,但与 c++ 非常相似,“rng”每次都能为我提供相同的随机数结果。但是在c ++中,这是通过清除c ++中的种子来解决的,所以我想知道这在c#中是否也可能?
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

您很可能每次都使用一个新实例。不应以可重复方式实例化。Randomnew Random(seed_here)


Random r = new Random(); //Do this once - keep it as a (static if needed) class field 

     

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

     Console.WriteLine($"{r.Next()}");

}

更新

下面是一个更复杂的示例:


class MyClass

{

    //You should use a better seed, 1234 is here just for the example

    Random r1 = new Random(1234); // You may even make it `static readonly`


    public void BadMethod()

    {

        // new Random everytime we call the method = bad (in most cases)

        Random r2 = new Random(1234); 


        for (int i = 0; i < 3; i++)

        {

            Console.WriteLine($"{i + 1}. {r2.Next()}");

        }

    }


    public void GoodMethod()

    {


        for (int i = 0; i < 3; i++)

        {

            Console.WriteLine($"{i+1}. {r1.Next()}");

        }

    }

}

class Program

{

    static void Main(string[] args)

    {

        var m = new MyClass();


        m.BadMethod();

        m.BadMethod();

        m.GoodMethod();

        m.GoodMethod();


    }

}

输出


1. 857019877

2. 1923929452

3. 685483091    

1. 857019877  <--- Repeats

2. 1923929452

3. 685483091

1. 857019877

2. 1923929452

3. 685483091

1. 2033103372 <--- Phew! It's a new number

2. 728933312

3. 2037485757


查看完整回答
反对 回复 2022-08-20
  • 1 回答
  • 0 关注
  • 85 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号