在一个范围内使用C#生成一个随机数

我如何去产生一个范围内的随机数字?

你可以试试

Random r = new Random(); int rInt = r.Next(0, 100); //for ints int range = 100; double rDouble = r.NextDouble()* range; //for doubles 

看一下

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

就像是:

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

尝试下面的代码。

 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 

使用:

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

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

  • 堆栈溢出问题生成(U)Int64和Decimal(伪)随机约束值

  • C#RandomProvider类

 // this is the code to generate numbers of Triangular series // [1,3,6,10,15,21,......n] int result=0; int count=0; Console.WriteLine("What is your range"); int range = int.Parse(Console.ReadLine()); Console.Clear(); for (int i = 0; i < range; i++) { count= count++; result = (result + count); Console.WriteLine(result); }