I am still new to C# and I am trying to build a short program that simulates flipping a coin X number of times:
// Declarations
int headCount = 0;
int tailCount = 0;
// Main Program Logic
Console.WriteLine("Press enter to begin");
Console.ReadLine();
for (int x = 1; x <= 25; x++)
{
Random rnd = new Random();
int flip = rnd.Next(1, 3);
if (flip == 1)
{
Console.WriteLine("Heads");
headCount++;
}
else
{
Console.WriteLine("Tails");
tailCount++;
}
}
Console.WriteLine("Heads came up {0} times.", headCount);
Console.WriteLine("Tails came up {0} times.", tailCount);
if (headCount > tailCount)
{
Console.WriteLine("Heads wins.");
}
else
{
Console.WriteLine("Tails wins.");
}
// END OF DOCUMENT
Console.ReadLine();
}
Now, I am confident that my code is solid, however, I encounter a problem when I run the program. In the code above, the idea is that each time the for loop is executed that a new random number (either 1 or 2) is generated. In reality, 9 times out of ten, it generates one number the first time and then uses that number for the rest of the loop's executions.
Everyone once in a while, the results are about 50/50 (what you would statistically expect), but usually it is just the same result repeated 25 times.
Note that I declare the flip variable inside the loop. I have moved it back and forth from in the loop and just before the loop and the changes seem to not have any effect.
Am I doing something wrong or does C# like to throw out statistical anomalies?