How to generate random numbers in C#?

In C#, you can generate random numbers using the Random class. Here is a simple example:

// 创建一个Random对象
Random random = new Random();

// 生成一个0-100之间的随机整数
int randomNumber = random.Next(0, 101);

// 打印随机数
Console.WriteLine(randomNumber);

In the example above, we first create a Random object, then use the Next method to generate a random integer between 0 and 100, assigning it to a variable called randomNumber. Finally, we use the Console.WriteLine method to print out the random number.

Please note that each time the program is run, the generated random number will be different. If you want the program to generate the same random number every time it is run, you can pass a seed value when creating the Random object, for example:

Random random = new Random(42); // 使用种子值为42的Random对象

In this way, the same random number sequence will be generated every time the program is run. The seed value can be any integer.

bannerAds