Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# &引用;新随机(x)“;总是生成相同的数字吗?_C#_Random - Fatal编程技术网

C# &引用;新随机(x)“;总是生成相同的数字吗?

C# &引用;新随机(x)“;总是生成相同的数字吗?,c#,random,C#,Random,我试图得到一个唯一的随机数,但每次运行代码时,我总是得到相同的数。我会先得到14,然后是6,但我保存所有使用过的数字的列表似乎不起作用。手动添加14可以起作用,但当我添加randInt时,它不起作用 const int numCards = 32; List<int> usedCards = new List<int>(); int randInt = 0; Random rand = new Random(numCards

我试图得到一个唯一的随机数,但每次运行代码时,我总是得到相同的数。我会先得到14,然后是6,但我保存所有使用过的数字的列表似乎不起作用。手动添加14可以起作用,但当我添加randInt时,它不起作用

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);
const int numCards=32;
List usedCards=新列表();
int-randInt=0;
Random rand=新的Random(numCards);
增加(14);
做
{
randInt=rand.Next(0,numCards);
Show(randInt.ToString(),“游戏结束”,MessageBoxButtons.OK,MessageBoxIcon.惊叹号);
}
while(usedCards.Contains(randInt));
usedCards.Add(randInt);
更换:

Random rand = new Random(numCards);

在调用中提供一个固定的种子值(
numCards
始终具有相同的值)将导致一个可预测的、可重复的序列,该序列对于相同的种子值总是相同的,就像这样(不完全相同,但该点仍然有效):

例如,在我的机器上,使用
1
的固定种子并绘制从0到100的10个数字,总是生成序列

24,11,46,77,65,43,35,94,10,64
另一方面,如果不使用种子值,序列将变得不可预测

如果没有传入种子值,
Random
将基于当前时间生成一个新的种子值,这就是您想要获得一个新的随机数序列的原因-如果您不以快速顺序再次初始化它,这就是为什么您应该重复使用
Random
实例,而不是每次都重新创建它们。

如果为随机类构造函数指定一个种子值,它每次都会生成相同的序列。产生随机数序列的算法是确定性的

如果使用不带参数的构造函数,则随机对象将在当前时间使用种子值,因此使用此构造函数实例化的每个随机对象将具有不同的随机数序列,只要时间种子值可能不同

如果两个不同的随机对象在时间上非常接近,则仍然可以从它们中获得相同的数字序列


对不起,在这种情况下需要包括这一点:@David Z:为什么?那根本不是一回事。谢谢,我相信现在可以了。现在,关于我的代码的其他问题,答案很好。非常好的图片:)您在赌场中找到了程序算法的一部分。:)@阿列克谢:那是另一个错误——每次使用都会产生一个新的
Random
。@AlexeiLevenkov“几乎”,但这更。。。具体的然而,这是一个很好的相关问题。
24,11,46,77,65,43,35,94,10,64