2015-04-06 53 views
2
Console.WriteLine("How many times would you like to roll?"); 
string count = Console.ReadLine(); 
int cnt = Convert.ToInt32(count); 

for (int i = 1; i <= cnt; i++) 
{ 
    int rol = new int(); 
    Random roll = new Random(); 
    rol = roll.Next(1, 6); 
    Console.WriteLine("Die {0} landed on {1}.", i, rol); 
} 

Console.ReadLine(); 

我想在C#中创建一个骰子滚动模拟器,但我遇到了一个问题:在第一次滚动后,随机数永远不会改变。发生了什么,我该如何解决它?随机函数刷新

+3

在'for'循环之外移动'Random roll = new Random()'。 – Alex 2015-04-06 02:09:25

回答

2

正如Alex指出的那样,您需要将其移出for循环。此外,通过一个使用1,7,而不是1,6这样你会得到1结果6

Console.WriteLine("How many times would you like to roll?"); 
string count = Console.ReadLine(); 
int cnt = Convert.ToInt32(count); 
Random roll = new Random(); 
for (int i = 1; i <= cnt; i++) { 
    int rol = new int(); 

    rol = roll.Next(1, 7); 
    Console.WriteLine("Die {0} landed on {1}.", i, rol); 
} 
Console.ReadLine(); 
+0

你完成了我的回答! :P(+1) – 2015-04-06 02:14:49

0

Random将创建pseudo-random号码之一。该序列的随机数由种子编号控制。如果它们的种子是相同的,则两个随机数序列将是相同的。序列中的数字是随机的:从某种意义上说,您无法预测序列中的下一个数字。

如果是Random,种子从哪里来?这取决于使用哪个构造函数。 Random()创建默认种子。 Random(Int32)使用调用代码传递的种子。

O.P.中的代码在循环的每次迭代中创建一个新的随机数生成器对象。每一次,种子都是相同的默认值。每次,伪随机数序列中的第一个数字都是相同的。

因此,在循环的外部创建一个Random,并在循环的每次迭代中使用相同的Random

 Console.WriteLine("How many times would you like to roll?"); 
     string strCount = Console.ReadLine(); 
     int n = Convert.ToInt32(strCount); 

     Random die = new Random(); 
     for (int i = 1; i <= n; i++) 
     { 
      int roll = die.Next(1, 6); 
      Console.WriteLine("Die {0} landed on {1}.", i, roll); 
     } 

     Console.ReadLine();