我写了一个简单的代码,我想防止重复的随机数。
最简单的方法是什么?
Random rnd = new Random();
int n1, n2, n3, n4, n5, n6, n7;
n1 = rnd.Next(1, 37);
n2 = rnd.Next(1, 37);
n3 = rnd.Next(1, 37);
n4 = rnd.Next(1, 37);
n5 = rnd.Next(1, 37);
n6 = rnd.Next(1, 37);
n7 = rnd.Next(1, 7);
Console.WriteLine("1 Number ({0})", n1);
Console.WriteLine("2 Number ({0})", n2);
Console.WriteLine("3 Number ({0})", n3);
Console.WriteLine("4 Number ({0})", n4);
Console.WriteLine("5 Number ({0})", n5);
Console.WriteLine("6 Number ({0})", n6);
Console.WriteLine("Additionl Number ({0})", n7);
}
}
}
答案 0 :(得分:-1)
我遇到了同样的问题。请改用:
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public int RandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return random.Next(min, max);
}
}
用法
int randomNumber = RandomNumber(0, 10); // random number between 0 and 10