我如何在一个范围内产生随机数?


当前回答

除了生成整数和双精度精度的随机类,考虑:

生成(U)Int64和Decimal的(伪)随机约束值 c#随机提供程序类

其他回答

试试下面的代码。

Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51

除了生成整数和双精度精度的随机类,考虑:

生成(U)Int64和Decimal的(伪)随机约束值 c#随机提供程序类

你可以试试

//for integers
Random r = new Random();
int rInt = r.Next(0, 100);

//for doubles
int range = 100;
double rDouble = r.NextDouble()* range;

看一看

随机类别,随机。Next方法(Int32, Int32)和Random。NextDouble方法

喜欢的东西:

var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);

Use:

Random r = new Random();
 int x= r.Next(10);//Max range