简体   繁体   English

如何在C#中使用随机数生成器?

[英]How to use a Random number Generator in C#?

I created a Windows Forms application using Visual Studio Professional in C#. 我在C#中使用Visual Studio Professional创建了Windows窗体应用程序。 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. 在我的程序中,我提示用户输入他/她想要的卷数,然后他们按Enter键以获取数字。

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 times the user wants. 我希望同一程序出现用户想要的次数。 I tried a for loop but couldn't get what I wanted. 我尝试了for循环,但无法获得想要的结果。

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 您不需要毫秒位,种子使它更加随机

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. 或者,数字可能不是随机的,因为循环太紧了,它将使用与内部生成器中的种子相同的时间。

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. 用用户想要的卷数替换number_of_rolls_the_user_wants result will hold the result. result将保留结果。

Also please note that, if you generate many random numbers in a short time, use the same Random object ! 还请注意,如果您在短时间内生成许多随机数,请使用相同的Random对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM