How to use a Random number Generator in C#?
I created a Windows Forms application using Visual Studio Professional in C#. In my program I prompt the user to input the number of rolls he/she wants and then they press enter to get the numbers.
The numbers are shown in the same form under a label and get tallied up. I know how to tally the numbers know but I can't get the random number generator to generate the number of rolls the user inputs.
This is what i am doing:
Random randGen = new Random;
int oneRoll = randGen.Next(1,7) + randGen(1, 7);
I want the same program to occur the number of开发者_StackOverflow中文版 times the user wants. I tried a for
loop but couldn't get what I wanted.
Make sure you create the Random Number generator just once.
Do NOT create it in each loop iteration.
Or, the numbers may not be random because the loop is so tight it will use the same time as the seed in the internal generator.
Try something like this:
Random randGen = new Random();
var rolls = new List<int>();
int sum = 0;
for (int i = 0; i < numberOfRolls; i++)
{
int randomNum1 = randGen.Next(1,7);
int randomNum2 = randGen.Next(1,7);
sum += randomNum1 + randomNum2;
rolls.Add(randomNum1);
rolls.Add(randomNum2);
}
Now all the separate rolls are in rolls, and the sum of them has already been calculated.
Edited to roll two dice, record them individually, and sum it all together.
int rolls = Console.ReadLine();
int total = 0;
Random randGen = new Random(System.DateTime.Now.Millisecond);
for(int i =0; i<rolls; i++)
{
int oneRoll = randGen.Next(1,7) + randGen.Next(1, 7);
Console.WriteLine("Rolled " + oneRoll);
total += oneRoll;
}
Console.WriteLine("Total " + total);
NB. you don't need the Millisecond bit, the seed just makes it more random
Your code is totally wrong...
Random randGen = new Random(DateTime.Now.Ticks); // unique seed, mostly
int result = 0;
for (int i = 0; i < number_of_rolls_the_user_wants; i++)
result += randGen.Next(2, 14); // (1 - 7) + (1 - 7) = 2 - 14 lol... >.>
Replace number_of_rolls_the_user_wants
with the number of rolls the user wants.
result
will hold the result.
Also please note that, if you generate many random numbers in a short time, use the same Random
object!
精彩评论