关于Random的疑问

.Net技术 码拜 8年前 (2016-05-08) 1070次浏览
无聊做着玩一个应用random生成机选彩票的小程序。
遇到一个问题求高手解惑。
代码如下:

public string GetCaipiao()
        {
            Random ran = new Random();
            int[] arr = new int[7];
            for (int i = 0; i < arr.Length; i++)
            {
                int RandKey = ran.Next(1, 33);  //产生一个1-35之间的数
                do
                {
                    RandKey = ran.Next(1, 33);
                }
                while (arr.Contains(RandKey));
                arr[i] = RandKey;
            }
            arr = GetArray(arr);//排序
            StringBuilder sb = new StringBuilder();
            //输出
            foreach (int num in arr)
            {
                sb.Append(num.ToString());
                if (num != arr[arr.Length - 1])
                    sb.Append(",");
            }
            int x = ran.Next(1, 16);
            sb.Append("+" + x);
            return sb.ToString();
        }

这个是生成一注彩票。

int n = 0;
            StringBuilder str = new StringBuilder();
            switch (cbx_Time.Text)
            {
                case "1":
                    str.Append(GetCaipiao());
                    break;
                case "5":
                    while (n < 5)
                    {
                        str.AppendLine(GetCaipiao());
                        n++;
                    }
                    break;
                default:
                    for (int i = 0; i < 10; i++)
                    {
                        str.AppendLine(GetCaipiao());
                    }
                    break;
            }
            txt_Show.Text = str.ToString();

但是为什么当本人一次生成五注的时候,五注都是一样的。这跟random的特性有什么关系吗,
而且打了断点以后再执行,五注到是不一样了,求高手大致解释一下

解决方案

10

Random ran = new Random();
默认是用时间当的种子,原因是程序运行的很快,所以短时间内随机出来的数字都一样
一般的用法,要不每次你用不同的种子来取随机数,要不就是你用同一个Random对象来生成不同的随机数

20

Random说明书(特别是备注第二段第二句):
https://msdn.microsoft.com/zh-cn/library/h343ddh9(v=vs.100).aspx

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于Random的疑问
喜欢 (0)
[1034331897@qq.com]
分享 (0)