Produce a random number in a range using C#

2019-01-03 08:57发布

How do I go about producing random numbers within a range?

标签: c# .net random
6条回答
成全新的幸福
2楼-- · 2019-01-03 09:13

Try below code.

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
查看更多
疯言疯语
3楼-- · 2019-01-03 09:26

Use:

Random r = new Random();
 int x= r.Next(10);//Max range
查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-03 09:28

You can try

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

Have a look at

Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method

查看更多
在下西门庆
5楼-- · 2019-01-03 09:31

For future readers if you want a random number in a range use the following code:

public double GetRandomNumberInRange(double minNumber, double maxNumber)
{
    return new Random().NextDouble() * (minNumber - maxNumber) + minNumber;
}

C# Random double between min and max

查看更多
Ridiculous、
6楼-- · 2019-01-03 09:34

Something like:

var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);
查看更多
迷人小祖宗
7楼-- · 2019-01-03 09:34

Aside from the Random Class, which generates integers and doubles, consider:

查看更多
登录 后发表回答