我如何在一个范围内产生随机数?
当前回答
Use:
Random r = new Random();
int x= r.Next(10);//Max range
其他回答
以下是Darrelk回答的更新版本。 它是使用c#扩展方法实现的。 它不会在每次调用此方法时分配内存(new Random())。
public static class RandomExtensionMethods
{
public static double NextDoubleRange(this System.Random random, double minNumber, double maxNumber)
{
return random.NextDouble() * (maxNumber - minNumber) + minNumber;
}
}
用法(确保导入包含RandomExtensionMethods类的命名空间):
var random = new System.Random();
double rx = random.NextDoubleRange(0.0, 1.0);
double ry = random.NextDoubleRange(0.0f, 1.0f);
double vx = random.NextDoubleRange(-0.005f, 0.005f);
double vy = random.NextDoubleRange(-0.005f, 0.005f);
你可以试试
//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方法
试试下面的代码。
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
喜欢的东西:
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