随机生成器抛出相同的结果

时间:2017-09-20 19:50:41

标签: c# random

我遇到了一个问题:当在C#中创建一个表单来为textBox字段分配随机数时,我总是得到相同的数字。即。

1 1
1 1
1 1
1 1

关于它的疯狂之处如下:调试时我会得到不同的数字。这是源代码:

namespace BlaBla
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = homeGame().ToString();
            textBox2.Text = awayGame().ToString();

            textBox3.Text = homeGame().ToString();
            textBox4.Text = awayGame().ToString();

            textBox5.Text = homeGame().ToString();
            textBox6.Text = awayGame().ToString();

            textBox7.Text = homeGame().ToString();
            textBox8.Text = awayGame().ToString();

        }

        private int homeGame()
        {
            int homeGoal = 0;
            Random rdHome = new Random();
            int homeNumber = rdHome.Next(0, 72);

            if (homeNumber < 10)
            {
                homeGoal = 0;
            }
            if (homeNumber > 10 && homeNumber < 36)
            {
                homeGoal = 1;
            }
            if (homeNumber > 35 && homeNumber < 56)
            {
                homeGoal = 2;
            }
            if (homeNumber > 55 && homeNumber < 71)
            {
                homeGoal = 3;
            }
            if (homeNumber > 70)
            {
                homeGoal = 4;
            }
            return homeGoal;
        }

        private int awayGame()
        {
            int awayGoal = 0;
            Random rdAway = new Random();
            int awayNumber = rdAway.Next(0, 700);

            if (awayNumber < 100)
            {
                awayGoal = 0;
            }
            if (awayNumber > 100 && awayNumber < 411)
            {
                awayGoal = 1;
            }
            if (awayNumber > 410 && awayNumber < 506)
            {
                awayGoal = 2;
            }
            if (awayNumber > 505 && awayNumber < 661)
            {
                awayGoal = 3;
            }
            if (awayNumber > 660)
            {
                awayGoal = 4;
            }
            return awayGoal;
        }

    }
}

我知道,这段代码不是世界上最好的。但有人知道这里有什么问题吗?请问修改后的代码分别是什么?

0 个答案:

没有答案