以下是一种更好的方法来生成一个范围内的随机不重复数字的C#代码:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        List<int> numbers = GenerateRandomNumbers(1, 10, 5);
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }

    public static List<int> GenerateRandomNumbers(int min, int max, int count)
    {
        if (count > max - min + 1)
        {
            throw new ArgumentException("Count cannot be greater than the range of numbers");
        }

        List<int> numbers = new List<int>();
        Random random = new Random();

        while (numbers.Count < count)
        {
            int randomNumber = random.Next(min, max + 1);
            if (!numbers.Contains(randomNumber))
            {
                numbers.Add(randomNumber);
            }
        }

        return numbers;
    }
}

使用GenerateRandomNumbers方法,你可以指定一个范围的最小值和最大值,以及要生成的随机不重复数字的数量。此方法使用了一个List<int>来存储已生成的数字,并使用Random类生成随机数字。如果生成的数字已存在于列表中,则不会添加。

请注意,如果要生成的数字数量大于给定范围内的数字数量,将会抛出ArgumentException异常

C# 从一个范围内随机5个不重复的数字出来 有没有更好的做法

原文地址: https://www.cveoy.top/t/topic/ijJD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录