Skip to content

A very simple random problem-please help

Lior

Asked Mar 16, 2006, 5:55 AM EST1 answer
Share
LinkedInX
Hi all
I wrote a simple code that should generate two different random numbers.
I designed a window in which I placed two labels and one button.
On the button click event the lebels should show two different numbers between 3-19.
the problem is when I click the button the two labels always show the same number when I use the "F11" to see the step by step happening inside the code the resault come out OK. why isn't it goes that way when I run(F5) the program???
the code goes somthing like that:

private void button1_click(....)
{
      dieRoller myRoll = new dieRoller();
         label1.text = myRoll.Roller().ToString();
         label2.text = myRoll.Roller().ToString();
}

Class dieRoller
{
    public int Roller()
{
       int randNum;
       Random roll = new Random();

         randNum = (int)(roll.NextDouble()*16)+3;
         return randNum;
}
}

what is wrong here???

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    It's because the Random generator uses your system clock as the "seed" for the random number it's going to generate.

    When you step through, it works because you are allowing more time to go by as you step throught, therefore the numbers generated are now different. :)

    I'm not sure how to fix (it's been a while since I've used the random number generate) but there should be a way to pass a seed to the function.  Check out the Help for ideas.

    -Chris.
    0