C#中的Random.Next()方法用于返回非负随机整数。
语法如下-
public virtual int Next (); public virtual int Next (int maxVal);
上面的maxVal参数是要生成的随机数的互斥上限。
现在让我们看一个例子-
using System; public class Demo { public static void Main(){ Random r = new Random(); Console.WriteLine("Random numbers....."); for (int i = 1; i <= 5; i++) Console.WriteLine(r.Next()); } }
输出结果
这将产生以下输出-
Random numbers..... 1014639030 1510161246 1783253715 487417801 249480649
现在让我们来看另一个示例-
using System; public class Demo { public static void Main(){ Random r = new Random(); Random r2 = new Random(); Console.WriteLine("Random numbers....."); for (int i = 1; i <= 5; i++) Console.WriteLine(r.Next()); Console.WriteLine("\nRandom numbers from 1 to 10....."); for (int i = 1; i <= 5; i++) Console.WriteLine(r2.Next(10)); } }
输出结果
这将产生以下输出-
Random numbers..... 613432308 1705125884 1787561614 1243383842 2016323534 Random numbers from 1 to 10..... 2 7 8 5 9