简体   繁体   English

C#中的Loto游戏

[英]Loto game in c#

I m trying to make some kind of game with c#, its loto game there is 10 columns. 我试图用C#制作某种游戏,它的Loto游戏有10列。 The computer has to generate 6 numbers to fill that 10 columns, my code is like: 计算机必须生成6个数字来填充10列,我的代码如下:

public static int[] Get() 
    { 
        int[] a = new int[6];
        System.Random r = new System.Random();
        bool flag; int val; 
        for (int i = 0; i < a.Length; ++i)
        {
            flag = false; 
            do 
            { 
                val = r.Next(1, 50);
                for (int k = 0; k < i; ++k)     
                    if (a[k] == a[i])
                    { 
                        flag = true; 
                        break; 
                    } 
                a[i] = val; 
            } while (flag);  
        } 
        return a;
    }
    public static void Main()
    { 
        int[] a; 
        for (int i = 0; i < 10; ++i) 
        { 
            a = Get();
            foreach (int x in a)  
                Console.Write("{0} ", x);
            Console.WriteLine(); 
        } 
    }

but it gives result same, like 但结果却一样

4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
22 29 28 15 33 6

so whats wrong at my code. 所以我的代码出了什么问题。
Thank you 谢谢

The Random class is seeded from the system time. Random类是从系统时间开始的。
When you make lots of Random s in a row, they will end up getting created at the same time and will use the same seed. 当您连续创建许多Random ,它们最终将同时创建并使用相同的种子。

You should re-use the Random instance across calls to Get() . 您应该在对Get()调用中重新使用Random实例。

Becouse of random class, its default method takes time from computer's current time so you are calling that method at same time and results are same. 由于使用随机类,它的默认方法占用了计算机当前时间,因此您同时调用该方法,结果是相同的。 You can modify code as below 您可以如下修改代码

 public static int[] Get(System.Random r)
    {
        int[] a = new int[6];
        bool flag;
        int val;

        for (int i = 0; i < a.Length; ++i)
        {
            flag = false;

            do
            {
                val = r.Next(1, 50);
                for (int k = 0; k < i; ++k)
                    if (a[k] == a[i])
                    {
                        flag = true;
                        break;
                    }
                a[i] = val;
            } while (flag);
        }

        return a;
    }


    public static void Main()
    {
        int[] a;
        System.Random r = new System.Random();

        for (int i = 0; i < 10; ++i)
        {
            a = Get(r);

            foreach (int x in a)
                Console.Write("{0} ", x);
            Console.WriteLine();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM