Skip to main content
 首页 » 编程设计

c#之当我在 C# 的循环内声明 Random 时,它会给我非随机数之在我的循环外声明它会给我随机数。为什么

2024年02月13日14bhlsheji

<分区>

我正在制作一副纸牌。当我尝试洗牌时,我感到有些奇怪。

调用我的程序之前的构造函数经过了如下循环(伪代码,含)-

for i in (0,13): 
   for j in (0,3): 
      new Card(i,j) 

无论如何,这是简化的形式。基本上会生成一张带有数字和花色的卡片。现在问题代码(C#):

private void Shuffle() 
{ 
    List<Card> newList = new List<Card>(); 
    while (cards.Count > 0) 
    { 
        Random r = new Random(); 
        int next = r.Next(0,cards.Count); 
        Console.WriteLine(next); 
        Card cur = cards.ElementAt(next); 
        newList.Add(cur); 
        cards.Remove(cur); 
    } 
    this.cards = newList; 
} 

这给了我半可预测的输出 - 即以下内容:

18 18 18 17 17 17 16 16 15 15 15 14 14 14 13 13 13 12 12 12 11 11 11 10 10 10 9 9 9 8个 8个 8个 7 7 7 6个 6个 6个 5个 5个 5个 4个 4个 3个 3个 3个 1个 5个 4个 3个 2个 2个 1个 0

接近尾声它似乎打破了模式,但我不确定为什么。再次运行它会得到不同但非随机的输出。

但是,如果我删除循环外的随机声明 -

    private void Shuffle() 
    { 
        List<Card> newList = new List<Card>(); 
        Random r = new Random(); /** THE ONLY DIFFERENT LINE **/ 
        while (cards.Count > 0) 
        { 
            int next = r.Next(0,cards.Count); 
            Console.WriteLine(next); 
            Card cur = cards.ElementAt(next); 
            newList.Add(cur); 
            cards.Remove(cur); 
        } 
        this.cards = newList; 
    } 

在这种情况下,我得到了更多看似随机的数字 -

19,28,21,2,16,20,33,26,7,36,31,33,33,26,34,4,18,20,13,27,16,11,18,22 ,18,21,21,8,22,12,6,17,2,17,0,11,2,14,9,0,8,10,1,7,4,1,0,0,2 ,1,0,0

当我从 Visual Studio 发布代码并运行输出程序时,这种差异似乎消失了。我对发生了什么感到困惑。由于我有 4 个核心,这是否会在同一毫秒内将进程分配给 4 个核心,从而使用相同的数字作为其种子?但是,当我发布代码时,这对于为什么它能正常工作是没有意义的......