简体   繁体   English

麻烦C#随机类

[英]Trouble with C# Random class

I've got a class that represents a coin, which can be flipped with the Coin.Flip() method. 我有一个代表硬币的类,可以使用Coin.Flip()方法翻转。 Flip() uses random.Next(2); Flip()使用random.Next(2); to get either a 0 or a 1 representing heads or tails. 获得表示头部或尾部的0或1。 This works good.. sort of. 这很好..有点。

For the program, I need to have 2 coins, which I make, lets say coin1 and coin2. 对于程序,我需要有2个硬币,我可以说硬币1和硬币2。

coin2 always needs to be flipped straight after coin1, which I can do with: coin2总是需要在coin1之后直接翻转,我可以用:

coin1.Flip();
coin2.Flip();

That should work, right? 那应该有用,对吗?

Well it doesn't! 好吧,它没有! Every time I run those two lines of code, both coins end up with the same values as each other! 每次我运行这两行代码时,两个硬币最终都会有相同的值!

The face value is stored in face inside the Coin class, which is defined like this: 面值存储在Coin类中的face中,其定义如下:

private int face;

I don't see anything wrong with what I've done, yet every single time I run the code, they end up identical. 我没有看到我所做的事情有任何问题,但每次运行代码时,它们最终都是相同的。

Oh, also, random is defined in the Coin class as well like so: 哦,同样,随机也是在Coin类中定义的,如下所示:

private Random random = new Random();

Thanks for your help! 谢谢你的帮助!

EDIT: Here's Flip(), it works now that random is static though. 编辑:这是Flip(),它现在可以工作,即random是静态的。

    public void Flip() {
        face = random.Next(2);
    }

Random number generators need a seed value. 随机数生成器需要种子值。 RNG's with an identical seed will produce the same stream of random numbers. 具有相同种子的RNG将产生相同的随机数流。

By default, System.Random uses the current time as the seed. 默认情况下,System.Random使用当前时间作为种子。 If you create two instances almost immediately after each other, they will both likely have the same time value, and therefore will produce the same random number sequence. 如果您几乎立即创建两个实例,它们可能都具有相同的时间值,因此将生成相同的随机数序列。

You can move the Random to a static member so that all Coin's share the same RNG, but be aware that System.Random is not documented as threadsafe so you can't use multiple Coin's on different threads without some synchronization. 您可以将Random移动到静态成员,以便所有Coin共享相同的RNG,但要注意System.Random没有记录为线程安全,因此如果没有同步,您不能在不同的线程上使用多个Coin。

My guess is that you probably want to redefine your random variable, at the class level, as: 我的猜测是你可能想在课堂上重新定义你的random变量:

private static Random random = new Random();

This will make every call to Flip() use the same generator, and not reseed constantly. 这将使每次调用Flip()使用相同的生成器,而不是不断重新调度。 If you're creating the Random instance every call, and call two times very close together, you may get the same seed, and hence the same values. 如果您在每次调用时创建Random实例,并且两次非常接近地调用,则可能会获得相同的种子,因此值相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM