I have been playing around and wrote this little piece of code. I am trying to flip a coin defined number of times and then count how many tails and heads I am getting. So here it is:
private void Start_Click(object sender, EventArgs e)
{
int headss = 0;
int tailss = 0;
int random2, g;
string i = textBox1.Text;
int input2, input;
bool NumberCheck = int.TryParse(i, out input2);
if (textBox1.Text == String.Empty) // check for empty string, when true
MessageBox.Show("Enter a valid number between 0 and 100000.");
else // check for empty string, when false
if (!NumberCheck) // number check, when false
{
textBox1.Text = String.Empty;
开发者_StackOverflow社区MessageBox.Show("Enter a valid number between 0 and 100000.");
}
else
{
input = Convert.ToInt32(textBox1.Text);
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
if (random2 == 0)
{
headss++;
}
else if (random2 == 1)
{
tailss++;
}
}
}
heads.Text = Convert.ToString(headss);
tails.Text = Convert.ToString(tailss);
}
The problem is that I keep getting problems while displaying the content. It's not even close to display they right result. Any ideas?
EDIT. Solution: move following line 3 lines up :D
Random random = new Random();
Instead of
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
}
Declare a single Random
for use throughout:
private Random randomGenerator = new Random();
private void Start_Click(object sender, EventArgs e)
{
// ...
for (g = 0; g < input; g++)
{
random2 = randomGenerator.Next(2);
}
// ...
}
You should use only one Random object to generate good (as good as default Random does) random sequence.
The default constructor for random take the systmem time as seed. Therefore, if you generate lots of them in a short amount of time they will all generate the same sequence of random numbers. Pull the random object out of the loop and this effect will not occur.
With RandomGenerator
. This code will count how many times coin has been flipped. It will end with 3 consecutive HEADS.
private RandomGenerator rgen = new RandomGenerator ();
public void run () {
int value = 0;
int total = 0;
while (value != 3) {
String coinFlip = rgen.nextBoolean() ? "HEADS" : "TAILS";
println (coinFlip);
if (coinFlip == "HEADS") {
value+=1;
} else {
value=0;
}
total +=1;
}
println ("It took "+total+" flips to get 3 consecutive heads");
}
精彩评论