麻烦C#Random类 [英] Trouble with C# Random class

查看:300
本文介绍了麻烦C#Random类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示硬币,可与Coin.Flip()方法可翻转的类。
翻转()使用random.Next(2);得到无论是0或1代表正面或反面。这工作不错..那种。



有关程序,我需要有2个金币,这是我做,可以说COIN1和COIN2。



COIN2总是需要COIN1后直奔翻转,我可以做的:

  COIN1 .Flip(); 
coin2.Flip();

这应该工作,对不对?



那么它不!每次运行的代码这两行,既硬币最终获得彼此相同的值<!/ P>

面对值存储在面对硬币类,在其内部的定义是这样的:

 私人诠释的脸; 



我看不出什么毛病我都干了些什么,但每一次我运行。代码,他们最终一致



哦也,随机在硬币类中定义的,以及像这样:

 私人随机随机=新的随机(); 



感谢您的帮助!



编辑:这里是翻转(),它的工作原理现在随机是静态的,虽然

 公共无效翻转(){
脸= random.Next(2);
}


解决方案

随机数发生器需要一个种子值。 RNG与一个相同的种子将产生的随机数相同的流



默认System.Random使用当前时间作为种子。如果后彼此几乎立即创建两个实例,它们都将可能具有相同的时间值,并因此将产生相同的随机数序列



可以移动至随机到一个静态成员,让所有硬币的份额相同的RNG,但要知道,System.Random不记录为线程安全的,所以你不能使用多个硬币的在不同的线程没有一些同步。


I've got a class that represents a coin, which can be flipped with the Coin.Flip() method. Flip() uses random.Next(2); to get either a 0 or a 1 representing heads or tails. This works good.. sort of.

For the program, I need to have 2 coins, which I make, lets say coin1 and coin2.

coin2 always needs to be flipped straight after coin1, which I can do with:

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:

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:

private Random random = new Random();

Thanks for your help!

EDIT: Here's Flip(), it works now that random is static though.

    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.

By default, System.Random uses the current time as the seed. 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.

这篇关于麻烦C#Random类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆