Random.Next方法
一、重載
- Next():返回一個非負隨機整數
Random random= new Random();
Console.WriteLine("Generating 10 random numbers:");
for (int ctr = 1; ctr <= 10; ctr++)
{
int number = random.Next();
Console.WriteLine(number);
}
- Next(Int32):返回一個小於所指定最大值的非負隨機整數
Random random= new Random();
Console.WriteLine("Generating 10 random numbers:");
for (int ctr = 1; ctr <= 10; ctr++)
{
int number = random.Next(10);
//生成的隨機值小於10
Console.WriteLine(number);
}
- Next(Int32, Int32):返回在指定範圍內的任意整數
Random random= new Random();
Console.WriteLine("Generating 10 random numbers:");
for (int ctr = 1; ctr <= 10; ctr++)
{
int number = random.Next(1,10);
//生成的隨機值大於等於1小於10
Console.WriteLine(number);
}
Random.NextDouble方法
-
返回一個大於或等於 0.0 且小於 1.0 的隨機浮點數
-
示例
Random random= new Random();
Console.WriteLine("生成10個大於或等於0.0且小於1.0的隨機浮點數");
for (int ctr = 1; ctr <= 10; ctr++) {
double number = random.NextDouble();
Console.WriteLine(number);
}
//此方法返回的隨機數的實際上限爲0.99999999999999978
Random.NextBytes方法
- NextBytes(Byte[]):用隨機數填充指定字節數組的元素
- 示例
Random random= new Random();
Byte[] b = new Byte[10];
random.NextBytes(b);
Console.WriteLine("The Random bytes are: ");
for (int i = 0; i <= b.GetUpperBound(0); i++)
Console.WriteLine("{0}: {1}", i, b[i]);
// 示例運行後結果爲:
// The Random bytes are:
// 0: 131
// 1: 96
// 2: 226
// 3: 213
// 4: 176
// 5: 208
// 6: 99
// 7: 89
// 8: 226
// 9: 194
- 字節數組的每個元素都設置爲一個大於或等於0且小於或等於 MaxValue的隨機數