How to write code for generating random numbers in C#?

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

using System;

class Program
{
    static void Main()
    {
        // 创建Random对象
        Random random = new Random();

        // 生成一个随机整数
        int randomNumber = random.Next();

        // 输出随机整数
        Console.WriteLine(randomNumber);

        // 生成一个指定范围内的随机整数
        int randomNumberInRange = random.Next(1, 10);

        // 输出随机整数
        Console.WriteLine(randomNumberInRange);

        // 生成一个随机双精度浮点数
        double randomDouble = random.NextDouble();

        // 输出随机双精度浮点数
        Console.WriteLine(randomDouble);

        // 生成一个随机布尔值
        bool randomBool = random.Next(2) == 0;

        // 输出随机布尔值
        Console.WriteLine(randomBool);
    }
}

This sample demonstrates how to generate different types of random numbers using the Random class. Depending on your needs, you can choose to use one of the types.

bannerAds