"新的随机(X)"总是产生相同的号码? [英] "new Random(x)" always generates the same numbers?

查看:117
本文介绍了"新的随机(X)"总是产生相同的号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个唯一的随机数,但每次我运行代码的时候,我总是得到相同的号码。我会得到14首,然后6,但似乎我持有所有使用的号码列表并不work.adding 14手动工作,但是当我添加randInt这是行不通的。

  const int的numCards = 32; 
名单,LT; INT> usedCards =新的List< INT>();
INT randInt = 0;
随机兰特=新的随机(numCards);
usedCards.Add(14);

{

randInt = rand.Next(0,numCards);
MessageBox.Show(randInt.ToString(),游戏结束,MessageBoxButtons.OK,MessageBoxIcon.Exclamation);

}
,而(usedCards.Contains(randInt));

usedCards.Add(randInt);


解决方案

替换为:

 随机兰特=新的随机(numCards); 



 随机兰特=新的随机(); 



供应一个的固定的种子值( numCards 总是在 随机构造函数调用将导致的预测可重复性的序列,始终是相同的种子值相同,就像这样(不完全,但还是点有效):





例如使用 1 并提请10个数字,从0到100,我的机器的总是的生产序列

  24,11,46,77,65,43,35, 94,10,64 

使用,另一方面没有种子值,该序列变成不可预测的。



如果没有传递的种子值,随机将生成基于当前时间的新的种子值,那是什么你想获得的随机数的一个新的序列 - 只要你不快速订单重新初始化它,这就是为什么你应该重新使用随机实例,而不是重新创建他们每一次。


I am trying to get a unique random number but i always get the same number every time i run the code. i will get 14 first then 6 but my list for holding all the used numbers doesn't seem to work.adding the 14 manually works but when i add randInt it doesn't work.

const int numCards = 32;
        List<int> usedCards = new List<int>();
        int randInt = 0;
        Random rand = new Random(numCards);
        usedCards.Add(14);
        do
        {

            randInt = rand.Next(0, numCards);
            MessageBox.Show(randInt.ToString(), "End Game", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        while (usedCards.Contains(randInt));

        usedCards.Add(randInt);

解决方案

Replace:

Random rand = new Random(numCards);

with

Random rand = new Random();

Supplying a fixed seed value (numCards always has the same value) in the Random constructor call will result in a predictable, reproducible sequence which is always the same for the same seed value, just like this (not quite but still the point is valid):

For example using a fixed seed of 1 and drawing 10 numbers ranging from 0 to 100, on my machine always produces the sequence

24,11,46,77,65,43,35,94,10,64

Using no seed value on the other hand, the sequence becomes unpredictable.

Without a seed value passed in, Random will generate a new seed value based on the current time, that's what you want to get a new sequence of random numbers - provided you don't initialize it again in fast order, that's why you should re-use Random instances instead of re-creating them every time.

这篇关于&QUOT;新的随机(X)&QUOT;总是产生相同的号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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