C#中的随机数

时间:2011-09-28 16:41:52

标签: c# random

  

可能重复:
  Random number generator not working the way I had planned (C#)

我创建了一个方法,它返回一个随机数:

public static int SelectRandomMachine(int max)
{
int seed = (int)DateTime.Now.Ticks;
Random rndNumber = new Random(seed);
int randMachine = rndNumber.Next(0, max);
return randMachine;
}

如果我调用该方法两次,目前它返回的是相同的随机数:

randM1 = SelectRandomMachine(maxNumber);
randM2 = SelectRandomMachine(maxNumber);

任何建议都将受到高度赞赏。

5 个答案:

答案 0 :(得分:6)

提示看看这一行:

int seed = (int)DateTime.Now.Ticks;

如果您连续两次执行该行,您认为这些值是什么?

例如:

int seed1 = (int)DateTime.Now.Ticks;
int seed2 = (int)DateTime.Now.Ticks;

// Write it out *after* executing; console output can take a while
Console.WriteLine(seed1);
Console.WriteLine(seed2);

有关解决方案和更多信息,请参阅我的article on randomness

编辑:这是一个快速而肮脏的例子,说明缺少线程安全导致问题:

using System.Collections.Generic;
using System.Threading;

class Program
{
    const int Iterations = 1000000;
    static readonly Random rng = new Random();

    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        for (int i = 0;  i < 8; i++)
        {
            Thread t = new Thread(ExerciseRandom);
            threads.Add(t);
            t.Start();
        }
        foreach (Thread t in threads)
        {
            t.Join();
        }
        Console.WriteLine(rng.Next());
        Console.WriteLine(rng.Next());
        Console.WriteLine(rng.Next());
    }

    static void ExerciseRandom()
    {
        for (int i = 0; i < Iterations; i++)
        {
            rng.Next();
        }
    }
}

我的盒子上的输出:

0
0
0

答案 1 :(得分:2)

您需要创建一个Random对象的单个实例并多次调用它。

由于您的种子基于时间(滴答数),连续快速调用将最终生成相同的种子值,因此伪随机数生成器将生成相同的序列。

答案 2 :(得分:1)

使Random实例静态:

static Random rndNumber = new Random((int)DateTime.Now.Ticks);

public static int SelectRandomMachine(int max)
{
   int randMachine = rndNumber.Next(0, max);
   return randMachine;
}

答案 3 :(得分:0)

你需要有一个私有静态Random()并引用它来获取随机数,Jon和Oded是对的,你不能快速连续调用。

private static Random _rnd = new Random();
public static int SelectRandomMachine(int max)
{
//int seed = (int)DateTime.Now.Ticks;
//Random rndNumber = new Random(seed);
int randMachine = _rnd.Next(0, max);
return randMachine;
}

答案 4 :(得分:0)

随机数生成器使用算法生成数字。如果您使用相同的数字为算法播种,它将生成相同的数字序列。这意味着如果您每次使用数字为rand播种,然后拉出序列的第一个数字,您将始终获得相同的数字。您需要为rand播种一次,然后在同一个Next()对象上重复使用Rand