Random numbers in C#

前端 未结 6 624
我寻月下人不归
我寻月下人不归 2021-01-24 19:52

I get the error below when I try to run the application I am sure its something simple but I dont see it. What I am trying to do it when I click a button I have labeled Play. I

相关标签:
6条回答
  • 2021-01-24 20:40

    Setup one Random object and initialize it once.

    class Form1
    {
        ...
        Random rnd = new Random();
    }
    

    then to use it every time it is needed

    void RandomNumber(int min, int max)
    {
        int num = rnd.Next(min, max);
        ...
    }
    

    What happens everytime you call new() it re-seeds the random number and you may end up with the same numbers over and over. I have had this happend to me and it killed me

    0 讨论(0)
  • 2021-01-24 20:42

    Well, your code doesn't match the error, but look at this:

    private void btnPlay_Click(object sender, EventArgs e)
    {
        RandomNumber();
    }
    
    private void RandomNumber(int min, int max)
    {
        int num = new Random().Next(min, max);
        lblPickFive_1.Text = num.ToString();
    }
    

    RandomNumber has two parameters, min and max. You haven't specified any in the call inside btnPlay_Click. That's what the compiler is complaining about. Change the call to something like:

    RandomNumber(5, 10);
    

    Even when that's fixed, you shouldn't create a new instance of Random each time. As it happens, it's unlikely to cause problems in this particular case as it's triggered by a user action, but you should read my article on random numbers to see what the problem is and how to avoid it.

    0 讨论(0)
  • 2021-01-24 20:44

    You need to pass in values:

    private void btnPlay_Click(object sender, EventArgs e)
    {
        RandomNumber();
    
    }
    

    should be:

    private void btnPlay_Click(object sender, EventArgs e)
    {
        RandomNumber(0, 50000);
    
    }
    
    0 讨论(0)
  • 2021-01-24 20:46

    First, you shouldn't be newing up a random number generator every time you want a new random number. You should set the generator as a static or member variable and refer to it for each new number.

    Second, you have to pass a min and a max to your RandomNumber method.

    0 讨论(0)
  • 2021-01-24 20:52

    You're calling RandomNumber(); in btnPlay_Click but the RandomNumber method requires min and max.

    0 讨论(0)
  • 2021-01-24 20:59

    Your RandomNumber method takes two arguments.

    If you want to call the method, you need to pass two arguments.

    0 讨论(0)
提交回复
热议问题