一、常用操作 NextDouble():返回0-1.0之间的随机数Next():返回非负随机整数(0-216)Next(i):返回一个小于i的非负随机整数Next(i,j):生成i
System.Random r = new Random();
s1 = r.NextDouble().ToString();//0.868992506465405
s2 = r.Next().ToString(); //1665548020
s3 = r.Next(10).ToString(); //5
s4 = r.Next(1000, 2000).ToString();//1885
byte[] buffer = new byte[255];
r.NextBytes(buffer);
s5 = buffer[254].ToString(); ;//207
时间间隔如果太短,创建的多个不同的Ramdom对象将具有相同的默认种子值,因而会产生几组相同的随机数。
System.Random r1 = new Random();
System.Random r2 = new Random();
Console.WriteLine(r1.Next().ToString());// 615672499
Console.WriteLine(r2.Next().ToString());// 615672499
使用单个Random对象生成所有随机数可避免此问题。
System.Random r = new Random();
Console.WriteLine(r.Next().ToString());// 1933637733
Console.WriteLine(r.Next().ToString());// 1799552041
System.Random r1 = new Random(1);
System.Random r2 = new Random(1);
System.Random r3 = new Random(2);
byte[] buffer1 = new byte[2];
byte[] buffer2 = new byte[2];
byte[] buffer3 = new byte[2];
r1.NextBytes(buffer1);
r2.NextBytes(buffer2);
r3.NextBytes(buffer3);
s1 = String.Join(",", buffer1);// 70,208
s2 = String.Join(",", buffer2);// 70,208
s3 = String.Join(",", buffer3);// 113,147
--结束END--
本文标题: C#中的随机数函数Random()
本文链接: https://lsjlt.com/news/149622.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0