C#用Random类中的NextBytes、Next和NextDouble方法生成不同范围内的随机数序列

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的随机数

你可能感兴趣的:(c#学习笔记,c#)