产生随机数 Random / RNGCryptoServiceProvider

 

Random.Next 方法 (Int32, Int32)

参数
minValue
类型: System.Int32
返回的随机数的下界(随机数可取该下界值)。
maxValue
类型: System.Int32
返回的随机数的上界(随机数不能取该上界值)。 maxValue 必须大于或等于 minValue。 
返回值
类型: System.Int32
一个大于等于 minValue 且小于 maxValue 的 32 位带符号整数,即:返回的值范围包括 minValue 但不包括 maxValue。 如果 minValue 等于 maxValue,则返回 minValue。 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Random_练习
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rd = new Random();
            for (int i = 0; i < 1000; i++)
            {
                int k = rd.Next(1, 101);
                Console.WriteLine(k);
            }
            Console.ReadKey();
        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace RNGCryptoServiceProvider_练习
{
    class Program
    {
        static void Main(string[] args)
        {
            //随机产生100个不重复的数(1-100)
            List<int> list = new List<int>();
            while (list.Count<100)
            {
                int num = RollDice(100);
                if (!list.Contains(num))
                {
                    list.Add(num);
                }
            }

            foreach (int item in list)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("=========" + list.Count + "=========");

            Console.ReadKey();
        }

        /// <summary>
        /// 产生随机数
        /// </summary>
        /// <param name="NumSides"></param>
        /// <returns></returns>
        public static int RollDice(int NumSides)
        {
            byte[] randomNumber = new byte[1];

            RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();

            //用一个随机值填充数组。
            Gen.GetBytes(randomNumber);

            //将字节转换为一个整数值,使模量操作更容易
            int rand = Convert.ToInt32(randomNumber[0]);

            return rand % NumSides + 1;
        }
    }
}

  

 

转载于:https://www.cnblogs.com/linyongqin/articles/4517259.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值