不显示随机数

时间:2016-12-19 21:43:11

标签: c#

每个人我都在大学上课,我正在努力寻找某个问题的解决方案。我有一个窗口,在启动时生成一个随机数,也是一个序列(按下按钮时)。问题是在序列期间显示相同的5个数字,而应该显示5个不同的数字。它们是随机生成的,就像单个数字

一样
     using System;
     using System.Threading.Tasks;
     using System.Windows.Forms;

      namespace RandomNumbers
     {
        public partial class frmRandomNumberGenerator : Form
{
    private bool generate = true;

    public frmRandomNumberGenerator()
    {
        InitializeComponent();
    }

    private string GenerateNumber(int min, int max)
    {
        return new Random().Next(min, max).ToString();
    }

    private void ToggleControls()
    {
        btnStart.Enabled = !generate;
        tcRandomNumbers.Enabled = !generate;
        txtRangeMin.Enabled = !generate;
        txtRangeMax.Enabled = !generate;
        btnStop.Enabled = generate;
    }

    private async void btnStart_Click(object sender, EventArgs e)
    {
        if(string.IsNullOrEmpty(txtRangeMin.Text) || string.IsNullOrEmpty(txtRangeMax.Text))
        {
            MessageBox.Show("Invalid range!");
            return;
        }

        int min = 0;
        int max = 0;

        bool result = int.TryParse(txtRangeMin.Text, out min);
        if (result) result = int.TryParse(txtRangeMax.Text, out max);
        if (result) result = max > min;

        if (!result)
        {
            MessageBox.Show("Invalid range!");
            return;
        }

        generate = true;
        ToggleControls();

        while (true)
        {
            if (!generate) break;
            if (tcRandomNumbers.SelectedIndex == 0)
            {
                lblSingleResult.Text = GenerateNumber(min, max);
            }
            else
            {
                lblSequenceFirst.Text = GenerateNumber(min, max);
                lblSequenceSecond.Text = GenerateNumber(min, max);
                lblSequenceThird.Text = GenerateNumber(min, max);
                lblSequenceFourth.Text = GenerateNumber(min, max);
                lblSequenceFifth.Text = GenerateNumber(min, max);
            }

            await Task.Delay(TimeSpan.FromSeconds(1));
        }
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        generate = false;
        ToggleControls();
     }
  }
   }

1 个答案:

答案 0 :(得分:1)

有关详细信息,请参阅链接的答案。

变化:

private string GenerateNumber(int min, int max)
{
    return new Random().Next(min, max).ToString();
}

要:

private Random rnd = new Random();

private string GenerateNumber(int min, int max)
{
    return rnd.Next(min, max).ToString();
}

另外,请注意" max"将包含在可能的返回值中。为此你需要:

return rnd.Next(min, max + 1).ToString();